Newsletter: Xanax and grapefruit Phentermine 30mg Buprenorphine Bulk phentermine Iothalamate Purchase cialis online Buy generic viagra 50 mg tramadol Oxcarbazepine Cialis drug prescription Viagra supplier Cefpodoxime 2mg xanax Yohimbe and viagra Prednisone Hydrocodone vicodin Phentermine effects on birth control Klonopin xanax Soma sleep Loprox Fastin Cheap phentermine no prescription Medroxyprogesterone Meridia better than phentermine Phentermine pill Buy online viagra securely Cialis generic Viagra without a perscription Deferoxamine Tolbutamide Phentermine and methamphetamine Phentermine quick Valium vicodin Cialis dysfunction erectile levitra viagra Alka seltzer Phentermine + sale Order fioricet online Mylan xanax Alphaprodine Non perscription generic cialis Lisinopril with viagra Dextrothyroxine Camphor Where can i buy viagra Protamine Dilantin Canadian cialis Micronase Free viagra order online Clomipramine Ticarcillin Tyropanoate Tinzaparin Ordering viagra Warfarin Imiquimod Phentermine hcl side effects Darvocet Cyclobenzaprine Oxyphenbutazone Probenecid Vytorin 5 mg diet pills Fentanyl Etretinate Custom hrt phentermine Best buy phentermine Buying viagra Alavert Drug test tramadol Lamotrigine Disulfiram Cyclothiazide Lowest price on phentermine Cheep paris france phentermine Dimenhydrinate Prescriptions on line phentermine Viagra without a prescription Cheap vicodin Miconazole Taking viagra or levitra as a booster for cialis Information phentermine shortage Cialis comparison levitra Valtrex University rochester viagra pfizer Buy xanax without prescription Nitric oxide viagra Celiprolol Cialis levivia viagra vs vs Avandia Non prescription viagra Levothyroxine Mepenzolate Phentermine weight loss pills Vancomycin Free viagra samples Phentermine pill online discount Clarinex Phentermine very cheap Cozaar Sulfonamides Methamphetamine Hexamethonium Meperidine Cialis Clozapine Adenosine Withdrawal from xanax Anafranil Feldene Drug loss phentermine weight Xanax look alike High cortisol level phentermine Spectinomycin Filing income tax phentermine Prozac drug interaction with xanax Buy cheap phentermine cod Ceforanide Injecting xanax Lodine leukemia symptoms Phentermine delivered cod Phentermine no credit card required Prednisone Thiotepa Treat crohns disease with viagra Buy cheap phentermine yellow Buy Xanax Phentermine picture Elavil Buy cheap no phentermine prescription On line viagra Phendimetrazine Cialis forums Xanax depression Buying viagra online Buy online phentermine shipping 90 $89 mastercard Viagra online order guide Lactulose Xanax online prescription Cheapest xanax online Xanax online no prescription Methixene Vicodin detox Cheap phentermine overnight delivery Purchase tramadol online Comparison viagra cialis levivia Laetrile Side effects of xanax mylan Buy cialis generic online 5mg cheap Cheap prices phentermine Xanax dosages Xanax ambien Alprazolam xanax Diethylstilbestrol No fax payday loan buy tramadol Oxycontin xanax bars perclesept and lortab Piperidolate Fluorouracil Can i take xanax with zocor and procardia Chlorhexidine Tretinoin Viagra class action Viagra sales online Lowest price for phentermine Epinephrine Thiabendazole Methadone xanax interaction Cod phentermine shipped Levallorphan Codeine Cephalexin Mexican pharmacy viagra Cialis viagra levivia Phentermine side effects dangers Elocon Klonopin vs xanax dosage Buy online order viagra Ampicilin Phenacetin Language phentermine ru Pill price viagra What is xanax Withdraw xanax Dangers of phentermine Soma san diego Anxiety disorder xanax Cheap 37 5 phentermine Phentermine use Lotrimin Primidone Cialis soft Dexchlorpheniramine Viagra faq Hydrocodone vicodin Estradiol Viagra online Viagra for woman Phentermine overnight shipping Buy online tramadol Drug interactions with cialis Akane soma Diet discount phentermine pill Mail order viagra online Compare generic viagra prices Phentermine mexican pharmacies online Cialis price comparison Meridia vs phentermine Cialis viagra Meridia Taking phentermine with antidepressants Cheap tramadol no prescription Women viagra Tramadol pharmacy Online pharmacy and phentermine Levitra vs cialis vs herbal Viagra online no prescription Avandamet Best generic viagra Phentermine yellow Is phentermine dangerous Viagra online pharmacy Meridia diet pill Free shipping phentermine Viagra uk sales Free ambien 2005 comment december leave viagra Phentermine 30 mg ordered with discover card Mobic Phentermine cheap Reliable same or next day phentermine purchase online Order vicodin online Paregoric Phentermine success story Compare phentermine price Phentermine and glaucoma Ephedrine Cialis for sale Viagra on line uk Methadone and xanax Phentolamine Viagra xenical Hetacillin Free pack sample viagra Rated online pharmacies for phentermine Cialis side effects Aspartame Adipex Actonel Viagra alternative and woman Phentermine lortab online Cruises soma Phentermine 37 5mg Hydrocodone overnight Lopressor Phentermine at cost with no prescription About phentermine Long term effects of xanax Phentermine buy best Buy discount cialis Buy online pharmacy viagra 5mg Prempro Cialis experience Cephradine Phentermine hydrochloride Online tramadol prescriptions Vicodin picture Crestor Cheapest phentermine 90 day orders Climara Metrizamide Hydrocodone apap Does viagra work for women Sufentanil Phentermine reviews Viagra alternatives Anafranil Diet pill addiction phentermine Gabapentin Discount online viagra Lethal dose of xanax Lethal doses of klonopin and xanax Phentermine 15mg Nonoxynol Buspar Xanax long term effects Phentermine drug interaction Phentermine free shipping Hydrocodone withdrawal Order xanax online Digoxin Online viagra Cheapest price phentermine online pharmacy Methantheline Macular degeneration caused by viagra Nolvadex Phentermine next day delivery Mephenytoin Aldara Paromomycin How fast can you loss weight with phentermine Amoxicillin Flurbiprofen Phentermine shortage Can xanax cause frontal lobe dementia Purchase soma Lopid Phentermine dosage Xanax doses Provera Viagra users Concerta Premarin Discount pharmacy phentermine Metrizoate Cefdinir Viagra prescription uk 10 min viagra Keppra Maprotiline Phentermine tricks Avandamet Accolate Viagra commercial Research phentermine tolerance Ambien cr Buy cheap online uk viagra Zyban Tramadol hydrochloride tablet Discount phentermine no prescription Side effects of viagra Luvox Try viagra for free Phentermine online pay with mastercard Snorting xanax Tetanus Sophia viagra Succinylcholine Aerobid Phentermine prescription online Probucol Xanax online without a prescription Biaxin Soma Hydrocodone info Phentermine from canada Does xanax show up on drug tests Dutasteride Flutamide Non prescription xanax 0 buy by popl powered viagra wordpress Discount meridia Diphenadione Diltiazem Buying viagra in the uk Free viagra Picture of soma Valium Online phentermine order Drug interaction xanax and holy basil Buy phentermine online cod Adipex phentermine weight loss Cialis impotence drug eli lilly co Xanax without prescription Arava Decadron Phentermine line Irbesartan Phendimetrazine Nizatidine Methaqualone Seroquel Coreg Cipro Canada viagra Cheapest phentermine online no prescription Bethanechol Xanax overnight Buy locally viagra Fenfluramine Lowest drug price for phentermine Rizatriptan Crohns phentermine Phenytoin interaction with xanax Phentermine prescriptions online Perscription phentermine Imiquimod Abbr href rel title title viagra Kaopectate Viagra female sexual inhancement Metronidazole Phentermine online diet pill Acyclovir Prescription order viagra online Hydrocodone cough Norethynodrel Methyclothiazide Snorting vicodin Blindness viagra Xanax overnight shipping Phentermine 15 mg Cheap soma Cialis commercial Klonopin versus xanax Norepinephrine Indapamide Physostigmine Nicoumalone Phentermine ephedrine Flagyl Liotrix Griseofulvin Us pharmacy phentermine Discount cialis online Clofazimine Biaxin What does phentermine look like Buy phentermine online same day delivery Recreational viagra use Phentermine shipped to missouri Buy viagra order viagra Phentermine capsules Tramadol hcl Dangers of taking xanax and neurontin Drug information on xanax History of phentermine use Zafirlukast Discount generic viagra Tramadol withdrawal Phentermine interactions Methazolamide Overnight phentermine Avalide Sertraline Discount drug phentermine Timolol Altace Phentermine and fast shipping Loxapine Cheap generic viagra online Tricor Valsartan Phentermine referring report urls Buy canada cialis Strattera Phentermine diet plan Where to buy phentermine online Order phentermine online Tramadol online pharmacy Levodopa Piperazine Zanaflex Ultracet Meloxicam Amsterdam holland viagra Addiction recovery xanax Overnight viagra Premphase 5 pay by money order Trimethoprim Order viagra without prescription Didanosine No prescription phentermine free shipping Oxyphencyclimine Cyclandelate Lowest phentermine 37 5 prices Losec Generic viagra uk Ceftizoxime Cialis soft tabs Dantrolene Chlorprothixene Neurontin Non prescription phentermine Aprotinin Cheap viagra uk Clarinex Phentermine no fees No prescription cialis Xanax without a prescription Eldepryl Viagra overnight Phentermine 37_5 Imdur Cheap viagra india Phentermine $89 Buy Phentermine Hydrocodone mexican pharmacy what is tramadol Generic viagra lowest prices Clindamycin Phentermine diet medication Hydrocodone guaifenesin Adapalene Buy phentermine online with pay pal Viagra substitutes Phentermine result Phentermine ship to ky Phentermine weight loss pill Mirtazapine Uk viagra supplier Prozac interact xanax Herbal phentermine Xanax death Phentermine and blood in stool Bromides Tramadol 200 mg Cefadroxil Lorazepam Zolpidem Ambien side effects Mercaptopurine Phentermine with master card Xanax drug interactions 2 mg xanax Buy domain onlinebigsitecitycom phentermine Chlortetracycline Cheap online phentermine prescription Flexeril Vinblastine Side effects of xanax xr Nitrofurantoin Colestipol Order phentermine c o d Phentermine uses Tapering off xanax Gentamicin Cheap viagra in uk Buy online purchase viagra Buy xanax online Ceclor Paroxetine Online pharmacy phentermine cod Captopril Toradol Buy viagra pill Crystal meth and xanax Amlodipine Buy cheapest viagra Nizoral Gitalin Apomorphine Buy Bontril Phentermine cod delivery Online phentermine pharmacy best cheapest Any drug interaction xanax and cold meds Natural viagra Fosfomycin Online xanax prescription Generic name online qoclick tramadol Phentermine blue 30 mg Flurazepam Mometasone Buy cialis in uk Long term side effects of phentermine Granisetron Norflex Cheap phentermine online withour prescription Filling online prescription viagra Secobarbital Viagra overdose Buy Ultram Phentermine able to beshipped to mo Xenical Xanax urine test Buy online securely viagra Canadian no phentermine prescription Viagra cialis Epoprostenol Buy viagra cheap Buy tramadol online without a prescription Soma online pharmacy Alcohol hydrocodone Cheap soma online Fioricet information Restoril Clindamycin Phentermine and glucophage Online cialis d method Buying phentermine Online ordering viagra Aura soma Cialis western open Xanax and drug testing Pioglitazone Viagra generic brand Mycostatin Tramadol saturday delivery Viagra dose Xanax libido Low price phentermine Cheap diet phentermine pill Viagra information India generic viagra How do i stop taking phentermine Free phentermine prescriptions Chlorpheniramine Viagra cream for woman Alfentanil American express phentermine Purchase hydrocodone Meridia versus phentermine Phentermine $70 no prescription Cefazolin Buy viagra now Buy viagra in canada Buy viagra 1 Viagra for women Shipping phentermine to florida Phentermine depression Viagra results Digitoxin Cheapest tramadol online Ketoprofen Buy viagra in uk Vicodin online pharmacy Purchase tramadol Phentermine side effects Cipro Picture of generic xanax Cause rebound weight gain phentermine Mexiletine Mebendazole Canada cialis Cheapest online viagra

Entries Comments



Category: PHP Basics

PHP Basic

PHP and Ajax: An Introduction

8 December, 2007 (04:29) | PHP Basics, ajax | By: passion@php

Introduction

Ajax is an acronym for Asynchronous Javascript and XML. It is basically a cross-platform mechanism which allows you to make fast, rich and responsive web pages. Using AJAX a coder can avoid reloading the web page when a part of it is changing because of the user interaction. So the AJAX engine which runs within the context of the browser handles basic tasks of validation and oter changes while the script dynamically retrieve some data from the application. This data transfer happens from browser to application in the background and so known as ‘Asynchronous mode of execution’.

Dynamic Script Loading

An alternate to XMLHTTP is dynamic script loading. It has a simple mechanism: you write a javascipt file and in your code you put a <script/> tag and assign the javascript file to its ‘src’ attribute so that it can be loaded when required. The following code explains this:


<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>Example 1
<script type=”text/javascript”>// function makeRequest() {
var oScript = document.createElement("script");
oScript.src = "example1.js";
document.body.appendChild(oScript);
}

function callback(sText) {
alert("Loaded from file: " + sText);
}
//]]>
</script>
</head>
<body>
<input type=”button” value=”Click Me” onclick=”makeRequest()” />
</body>
</html>

So you can see the <script/> element is created using the DOM createElement() method and add it to the page.

var oScript = document.createElement(”script”);
oScript.src = “/path/to/my.js”;
document.body.appendChild(oScript);

When the new <script/> element is actually added to the page then only downloading starts. Once downloading is done the JavaScript code is interpreted. The callback function is used to indicate that the code has finished being loaded and interpreted.

PHP Date and Time Functions and Time Zones

4 December, 2007 (14:43) | PHP Basics, date and time | By: passion@php

Introduction

These functions are basic tools used in many self-defined functions. PHP date and time functions are pretty straightforward to use if you understand the UNIX timestamp. They fall into three categories: returns the date or time, formats date or time, and validates date. UNIX timestamp measures time as a number of seconds since the beginning of the UNIX epoch(midnight Greenwich Mean Time on January 1, 1970).

Functions Returning the date and time

The fastest way to get a time is to use the time() function. This will return the UNIX timestamp for your locale. If you pass this timestamp to another function or program then it is the best format. But if you want to make human-readable, you have to format it.

If you want to measure performance the best utility to be used is microtime() function which returns the current time in seconds and microseconds since the UNIX epoch.

The main function used to return a date is getdate($timestamp). When used with the argument time(), as in getdate(time()), it returns an associative array with the following numeric elements derived from the UNIX timestamp –

seconds, minutes, hours, mday: day of the month(1-31), wday: day of the week(1-7), mon: month(1-12),year, yday: day of the year(1-365), weekday: day of the week( Sunday – Saturday) and month(January – December).

The date() function gives you the date and format it in one step. Without the timestamp as argument it returns you the current local date.

Functions Formatting the date and time

The main method to format a timestamp is using date($format…. $formatn[,$timestamp]). You pass a series of code indicating your formatting preferences, plus an optional timestamp.

The function strftime($format…. $formatn[,$timestamp]) is similar but specializes in formatting the time rather than date. The function gmstrftime($format…. $formatn[,$timestamp]) returns the time in formatted Greenwich Mean Time.

The function mktime() allows you to convert any date into a timestamp. It’s subtly different in the ordre of arguments from the UNIX command of the same name. The function gmmktime() gives the Greenwich Mean time.

Finally, the checkdate($month, $day, $year) allows you to quickly ensure that a particular date is a valid one, which is great help on leap-year questions.

User defined time zones

Problems occur when you take time and date information form an user whose time zone is not same as the time zone of the server. To convert this you need to have a location independent format for storing time in database and then again translate that to user’s local time. For that Greenwich Mean Time based timestamp is most neutral.

Functions and Variables Scope in PHP

4 December, 2007 (14:40) | PHP Basics, functions, variables | By: passion@php

Introduction

Scope is a technical term for the rules stating when a name (for a variable or function or any object) has the same meaning in two different places and when they mean differently.

Variable Scope

Any PHP variable that is not inside a function has global scope and extends throughout a given thread of execution. i.e., if you declare the variable at the top of a PHP file, it has the same meaning at end of the file and if not reassigned it will hold the same value. When you declare and assign a variable inside a PHP page, it assigns and reassigns the variable each time the page executes. Assignments of variables in one file do not affect variables of the same name in a different file , or even in other requests for the same file.

In some situations when you would like to hold onto information from one page to another you have numerous other techniques for that in PHP. For example, you can pass information from page to page using GET an POST variables, store information persistently in a database, associate it with a user session using PHP’s session handling mechanism, or store it in user’s hard disk via a cookie.

Variables assigned within a function are local to that function, and unless you make a special declaration in a function, that function won’t have access to the global variables declared outside the function.

Local Scope

The basic principle governing variables in function bodies is: each function has its own little world. One variable declared and assigned inside a function has nothing to do outside the function. The only variable values the function has access to are the formal parameter variables and any variable declared within the function.

The following code explains:


function myfunc()
{
$count = 0;
while($count < 10)
{
Print(chr(ord(‘A’) +$count));
$count = $count + 1;
}
Print(“
Counting $count letters”);
}
$count = 0;
myfunc();
$count = $count + 1;
Print(“ I am calling the function for $count times”);
$count = $count + 1;
Print(“ I am calling the function for $count times”);

The output will be:
ABCDEFGHIJ
Counting 10 letters
I am calling the function for 1 times
ABCDEFGHIJ
Counting 10 letters
I am calling the function for 2 times

Please observe both the function definition and the code outside the function has a variable called $count. But in the file it has file scope and inside the function it has function scope. And both are basically pointing to different memory spaces.

Global versus Local

The scope of a variable defined inside a function is local by default. Using the global declaration you can inform PHP that you want a variable name to mean the same memory space as it does in the context outside the function. Syntax of this declaration is simply the word global, followed by a comma-delimited list of the variables that should be treated that way. Let us consider a new version of the previous function


function myfunc()
{
global $count;
while($count < 10)
{
Print(chr(ord(‘A’) +$count));
$count = $count + 1;
}
Print(“
Counting $count letters”);
}
$count = 0;
myfunc();
$count = $count + 1;
Print(“ I am calling the function for $count times”);
$count = $count + 1;
Print(“ I am calling the function for $count times”);

The output will be:
ABCDEFGHIJ
Counting 10 letters
I am calling the function for 11 times
Counting 11 letters
I am calling the function for 12 times

This time the control does not go inside the while loop as it is already more than 10.

Function Scope

Functions in PHP scripts must be declared only once somewhere in the script which use them. The scope of function names is implicitly global. It is a good idea to define all the functions to be used before any code which uses them.

The syntax for function declaration:

function function_name(arguments if any) {
procedures
}

example:

function HelloJoe($string, $name) {
echo "$string $name";
}
$string = "Hello, ";
$name = "Joe";
HelloJoe($string, $name);

Output Buffering

4 December, 2007 (14:36) | PHP Basics, buffering | By: passion@php

Introduction

Output buffering is a comparatively newer concept in PHP. PHP provides some functions which allows a coder to buffer the output from a script and manipulate it in some useful way before sending it to the browser. It solves other problems too, like if you try to set a cookie, or send header information after sending some output PHP generates an error stating “Cannot modify header information - headers already sent”. This problem also could be solved using output buffering.

The Output Buffering in PHP

The process of output buffering ensures that no output is send to the visitor of the page until the script ended. Now the problem arises when you have a long-running script, and want some of the output to be flushed to the client, i.e., your browser, PHP output buffering functions allow that. Again you can completely wipe out some of the output from the buffer. Before starting the discussion and see some code, let us have a look in the output buffering functions of PHP.

The functions:

ob_start([callback function]) - Starts an output buffering session.
ob_flush() - Send the contents of the buffer to the client and clear the buffer.
ob_get_contents() - Returns the contents of the buffer. The buffer is not cleared.
ob_end_clean() - Ends the current buffering session and purges the buffer.
ob_end_flush() - Ends the current buffering session and displays the buffer.
ob_get_length() - (Version >= 4.0.2) Return the size of the current buffer.
ob_get_clean() - (Version >= 4.3) Composite of ob_get_contents() and ob_end_clean(). The buffer is returned and the session ends.

Let us start with a simple program, you want to redirect the user to another site and write the following code


<html>
<body>
<?php
echo "You will now be directed to google.com...\n";
header("Location: http://www.google.com");
?>
</body>
</html>

But this will generate the above mentioned error, as you can not set a cookie or a header after the output have been sent. So the solution would be to hold the output:


<?php
//start output buffering
ob_start();
?>
<html>
<body>
<?php
echo "You will now be directed to google.com...\n";
header("Location: http://www.google.com");
?>
</body>
</html>
<?php
//send the contents of the buffer to the browser
ob_end_flush();
?>

Next a callback function could be used with output buffering. It is probably the most powerful help of output buffering that is cn define a callback functions. Using this you can define a callback function and this function will be called only when the buffer is flushed. This function takes the buffer as a parameter. The value returned by the function is printed in the output.


<?php
function my_callback($content) {
$content = ' Will Smith';
return $content;
}
// Start output buffer with callback
ob_start('my_callback');
echo 'Hello';
?>

So the output will be Hello Will Smith

By this time you must have understood, that the ob_start() function creates a buffer (imagine it as a very long string, capable of storing lots of output) and starts buffering, and ob_end_flush() function flushes it out. The function ob_clean() is capable of cleaning the buffer if required and ob_flush() flushes it in the browser. Now, you can create more than one buffer in the script and nest them too. Before ending this discussion let us look into a nested buffer. The code is self explanatory.


<?php
// Open buffer #1
ob_start();
print "Line 1\n";
// Open buffer #2
ob_start();
print "Line 2\n";
// Grab the contents of buffer #2
$buf2 = ob_get_contents();
// Close buffer #2
ob_end_clean();
print "Line 3\n";
// Grab the contents of buffer #1
$buf1 = ob_get_contents();
// Close buffer #1
ob_end_clean();
// Output the buffer contents
print $buf1;
print $buf2;
?>

REST, XML-RPC, SOAP

25 November, 2007 (08:51) | webservices | By: passion@php

Introduction

Web services are Internet endpoints available most commonly through HTTP and HTTPS. The job of a web service is to consume HTTP requests. The messages have a specific schema applied to them, which in effect may be thought of as a transportable type system. Web services are also responsible for providing metadata describing the message both produced and consumed. The concept of web services can work, if and only if, the applications and servers follow a common language or protocols. XML is the undisputed choice for this, but there are some architectural differences in implementation, which led to three main Web services standards which are REST, XML-RPC, and SOAP.

REST

The term was coined by Roy Fielding in his Ph.D. dissertation [1] to describe an architecture style of networked systems. REST is an acronym g for Representational State Transfer. The name itself explains the idea. Web is composed of resources and a client or an application basically tries to access these resources. The client application traverses the hyperlink to reach the required URL and ultimately the resource in returned to the client. This in effect changes the state of the client. In other words, the client application changes or transfers state with each resource representation.

REST was meant to describe the nature of the web. It is not a standard but uses the standards:

HTTP, URL ,XML/HTML/GIF/JPEG/etc (Resource Representations)and text/xml, text/html, image/gif, image/jpeg, etc (MIME Types).

REST is in fact valuable for content-focused services. It works best when the resources are built as XML documents and the users can access it via HTTP Get. The entire system works on a tree of hyperlinks leading you to more details of the information, where the information is stored as XML documents. REST doesn’t have built-in support for complex types.

XML-RPC

While it seems obvious that the web is an excellent medium for distributing a user interface-oriented application, it may not seem so obvious that the same technology might be used to make method calls. One of the main reasons web services exist is different enterprises has agreed upon what a method call should look like and they all can access it over already existing HTTP connections. Web service method calls are encoded using XML. XML-RPC is the specification for making remote procedure calls over HTTP by using XML encoding.

REST was the specification used for simple XML data passing over HTTP, suitable for non-complex type data. In XML-RPC you call a specific function which is stored on the server or another machine and this function returns the data. Unlike REST this supports the PHP native types and other types like struct, date-time, base-64 binary data. It is similar SOAP but less complex.

An XML-RPC server takes an input that consists of a simple XML encoding of a method call sent as an HTTP POST. An example is as follows:


POST /xmlrpc-epi/xmlrpc-php-epi/sample/server.php HTTP/1.0
User-Agent: xmlrpc-epi-php/0.2 (PHP)
Host: localhost:80
Content-Type: text/xml
Content-Length: 191
<?xml version=’1.0’ encoding=’iso-8859-1’ ?>
<methodCall>
<methodName>greeting</methodName>
<params>
<param>
<value>
<string>World</string>
</value>
</param>
</params>
</methodCall>

Assume that greeting() is a function that takes a string input and returns a string output consisting of the string “Hello, “ prepended to the input string. It returns a response that is formatted in a similar way. An example is the following:


<?xml version=’1.0’ encoding=’iso-8859-1’ ?>
<methodResponse>
<params>
<param>
<value>
<array>
<data>
<value>
<string>Hello, World</string>
</value>
</data>
</array>
</value>
</param>
</params>
</methodCall>

SOAP

As mentioned before web method calls are encoded using XML. Another format that callers and services agree on is known as Simple Object Access Protocol (SOAP). The SOAP protocol is an XML formalization for message-based communication. SOAP defines how to format messages, how to bind messages over HTTP, and a standard error representation. Applications communicating using Remote Procedure Calls (RPC) between objects like DCOM and CORBA. But HTTP was not designed for this so RPC represents a compatibility and security problem. Firewalls and proxy servers naturally tend to block this kind of traffic. So SOAP was developed to allow communication over HTTP, as it is supported by all browsers and servers. SOAP provides a way to communicate between applications running on different operating systems, with different technologies and programming languages.

A SOAP message is also an XML document which contains the following:

  1. An Envelope element to identify the document as SOAP message.
  2. A Header element containing header information
  3. A Body element containing call and response information.
  4. A Fault element which gives information about error occurred during message processing. This is optional.

The following code shows an SOAP example:


POST /xmlrpc-epi/xmlrpc-php-epi/sample/server.php HTTP/1.0
User-Agent: xmlrpc-epi-php/0.2 (PHP)
Host: localhost:80
Content-Type: text/xml
Content-Length: 530
<?xml version=’1.0’ encoding=’’iso-8859-1’ ?>
<SOAP-ENV:Envelope
xmlns:SOAP-ENV=”http://schemas.xmlsoap.org/soap/envelope/”
xmlns:xsi=”http://www.w3.org/1999/XMLSchema-instance”
xmlns:xsd=”http://www.w3.org/1999/XMLSchema”>
<SOAP-ENV:Header>
...
</SOAP-ENV:Header>
<SOAP-ENV:Body>
<greeting>
<xsd:string>World</xsd:string>
</greeting>
</SOAP-ENV:Body>
</SOAP-ENV:Envelope>

The response may be something like the following:


<?xml version=’1.0’ encoding=’iso-8859-1’ ?>
<SOAP-ENV:Envelope
xmlns:SOAP-ENV=”http://schemas.xmlsoap.org/soap/envelope/”
xmlns:xsi=”http://www.w3.org/1999/XMLSchema-instance”
xmlns:xsd=”http://www.w3.org/1999/XMLSchema”>
<SOAP-ENV:Header>
...
</SOAP-ENV:Header>
<SOAP-ENV:Body>
<greetingResponse>
<SOAP-ENC:Array SOAP-ENC:arrayType=”xsd:string[1]”>
<xsd:string>Hello, World
</SOAP-ENC:Array>
</greetingResponse>
</SOAP-ENV:Body>
</SOAP-ENV:Envelope>

The SimpleXML API

15 November, 2007 (13:52) | PHP Basics, xml | By: passion@php

Introduction

SimpleXML API is new in PHP 5. It is basically an XML parser i.e. if you know an XML document’s layout, you can access the elements, attributes and the text data using SimpleXML parser’s in-built functionalities.

PHP XML Parsers

There are two types of XML Parsers.

  1. The Tree-based Parser: this type of parsers converts an XML document to a tree-based structure called ‘Document Object Model’ (DOM). This way it can analyse the entire document and provides different methods to access all the elements, attributes and text data. Example of this type of parser is DOM XML parser, which is part of core PHP.

  2. The Event-based Parser: this kind of parser considers and XML document as a series of events. So when an event occurs (like a node is encountered) the parser calls a specific event handler to handle it. Example of this type of parser is the Expat parser of core PHP.

What is SimpleXML API and how it works

SimpleXML API is another XML parser in PHP. It is part of PHP 5. It also works like DOM XML parser but instead of holding the entire document as a DOM object it stores the document’s elements as native PHP variables. So this parser is faster and easy to use. As it need not traverse the entire tree structure for every job. Most of the job requires an iterative job being done on some particular node. It dispenses with web standard with better flexibility, simplicity and better memory usage.

SimpleXML transforms the XML document into a SimpleXMLElement object. All the elements in the document are converted to this object’s attributes. If there is more than one level of elements those are stored into an array. Attributes of each is stored into an associative array, where attribute name corresponds to index. Text data of the element are converted to strings.

Using SimpleXML

SimpleXML is fast and flexible, it is used to read XML files, to extract data from XML strings and for editing text nodes or attributes.

The following functions are used to load an XML document, create the SimpleXMLElement object and manipulate it in various ways using the related arrays.

Function Description
addAttribute() Adds an attribute to the SimpleXML element
addChild() Adds a child element the SimpleXML element
asXML() Gets an XML string from a SimpleXML element
attributes() Gets a SimpleXML element’s attributes
children() Gets the children of a specified node
getDocNamespaces() Gets the namespaces of an XML document
getName() Gets the name of a SimpleXML element
getNamespaces() Gets the namespaces from XML data
registerXPathNamespace() Creates a namespace context for the next XPath query
simplexml_import_dom() Gets a SimpleXMLElement object from a DOM node
simplexml_load_file() Gets a SimpleXMLElement object from an XML document
simplexml_load_string() Gets a SimpleXMLElement object from an XML string
Xpath() Runs an XPath query on XML data

The following code shows the how the SimpleXML API can be used to get variable values out of an XML file with just a few lines of code.

<?php
$recipe = simplexml_load_file(“recipe.xml”);
$ingredients = $recipe->ingredients;
$directions = $recipe->directions;
$servings = $recipe->servings;
foreach ($ingredients as $ingredient)
{
print “<P>Ingredient: $ingredient”;
}
print “<P>Directions: $directions”;
print “<P>Serves $servings”;
?>

Using Loop Constructs in PHP

10 November, 2007 (12:21) | PHP Basics, loops | By: passion@php

Introduction

Loop structures are used to execute one or more lines of code repetitively. The following loop constructs are supported by PHP.

  1. The while loop
  2. The do….while loop
  3. The for loop
  1. The while Loop

    The while loop construct is used to execute a block of statements for a definite number of times, depending on a condition. The while statement always checks the condition before executing the statements within the loop. When the execution reaches the last statement in the while loop, the control is passed back to the beginning of the loop. If the condition still holds true, the statements within the loop are executed again. The execution of the statements within the loop continues until the condition evaluates to false.

    The following code is the syntax of the while loop construct:


    while (expression)
    {
    statements;
    }

    The following code is an example of the while loop construct:

    while (FALSE)
    print(“This will never print.<BR>”);
    If you want to run an infinite loop:
    while (TRUE)
    print(“All work and no play makes Jack a dull boy.<BR>”);
    To print a line 10 times:
    $count = 1;
    while ($count <= 10)
    {
    print(“count is $count<BR>”);
    $count = $count + 1;
    }

    The preceding code creates an integer variable count and stores 1 into it. Next part of the code checks whether count is reaching 10 and till so it prints the line stating the value of count. Once the value of count is 10 the loop terminates.

  2. The do…while Loop

    The do…while loop construct is similar to the while loop construct. Both iterate until the specified loop condition becomes false. However, in the do…while loop, the body of the loop is executed at least once and the condition is evaluated for subsequent iterations.

    The following code is the syntax of the do…while loop construct:

    do
    {
    statements;
    }while(expression)
    The following code snippet explains the do...while loop:
    $count = 45;
    do{
    print(“count is $count<BR>”);
    $count = $count + 1;
    }while ($count <= 10)

    It prints the single line:

    count is 45

  3. The for Loop

    The for loop structure is used to execute a block of statements for a specific number of times. The following code is the syntax of the for loop construct:


    for(initialization; termination; increment/decrement)
    {
    statements;
    }

    The initialization expression initializes the for loop construct. It is executed once at the beginning of the loop. The termination expression determines when to terminate the loop. At the beginning of the loop, this expression is evaluated for each iteration. When the expression evaluates to false, the loop terminates. Then, through the loop, the increment or decrement expression gets invoked after each iteration. All these components are optional.
    You can create an infinite loop by omitting all the three expressions, like:


    for( ; ; )
    {
    ....
    }

    The following code snippet explains for construct:

    for ($x = 1, $y = 1, $z = 1; //initial expressions
    $y < 10, $z < 10; // termination checks
    $x = $x + 1, $y = $y + 2, // loop-end expressions
    $z = $z + 3)
    print(“$x, $y, $z
    ”);

    would give the browser output:
    1, 1, 1
    2, 3, 4
    3, 5, 7

Register Global Variables

6 November, 2007 (12:49) | PHP Basics | By: passion@php

Introduction

Register_globals is a PHP directive. It’s value could be set on or off in PHP.ini file. When a user submits some variables to a PHP script for example, by posting a form, data from cookies or URL-encoded data etc., these variables are considered as global variables if the ‘register_globals’ directive is set as ‘on’. In such case the value of the variables are available to all the scripta and consequently could be tampered. This gives a security problem. On the other hand, if it is ‘off’(it is ‘off’ by default from PHP 4.2.0), you have to contact your host while upgrading your site. But the best practice is, as we are going to see, to use the predefined variables like $_ENV, $_GET, $_POST, $_COOKIE, or $_SERVER instead of using the more general $_REQUEST and initialise the important user-defined variables first.

Using Register Globals

As mentioned earlier form PHP 4.2.0 onwards register_globals directive is by default set to ‘off’. Previously it was ‘on’ by default and led to insecure coding practice. When set to ‘on’ it makes the Environment, GET, POST, Cookie and Server variables registered as global variables and allows the user to inject variables and values into the program.
The following examples explain the concept:

  1. Let us assume when our user with password ‘12345’ posts a form the control passes to the following code name test.php. Our user does not know the password but want the administrative privileges. The test.php is as follows

    <?php
    if (isset($_POST["password"]) && $_POST["password"] == "12345") {
    $admin = TRUE;
    }
    ?>

    Now by appending ?admin=1 to the URL of the page the user can set the value of admin to true. This is called injection. So when, register_globals is set to on user is able to inject variables into the program. In the above example, he/she can create a variable admin and set it’s value to 1.

  2. In this example the user can set the value of the variable authorized to true by injection. The code is explanatory.

    <?php
    // define $authorized = true only if user is authenticated
    if (authenticated_user()) {
    $authorized = true;
    }
    // Because we didn't first initialize $authorized as false, this might be
    // defined through register_globals, like from GET auth.php?authorized=1
    // So, anyone can be seen as authenticated!
    if ($authorized) {
    include "/highly/sensitive/data.php";
    }
    ?>

Best practice

  1. Setting up a .htaccess file : you can create a .htaccess file in the main directory of your site that has the PHP script and write the following code in that file.

    php_flag register_globals on

    You can set it to ‘off’ for testing your site.

  2. It is always recommended that register_globals is set to Off in your php.ini. but it considered better coding practice to always initialize your variables. We can change our previous example to:

    <?php
    $admin = FALSE;
    if (isset($_POST["password"]) && $_POST["password"] == "12345") {
    $admin = TRUE;
    }
    ?>

Rand () PHP Function

27 October, 2007 (13:18) | PHP Basics | By: passion@php

The rand() function is used to generate a random number in PHP. It can also be used to generate a random number within a specific range (for example a number between 10 and 30.) On some platforms, Windows for example, if unspecified the largest number that will be generated is 32768, however you can set a specific range to include higher numbers.

Examples:

<?php
print rand() . "<br>";
//generates and prints a random number
print rand(10, 30);
//generates and prints a random number between 10 and 30 (10 and 30 ARE included)
print rand(1, 1000000);
//generates and prints a random number between on and one million
?>

FTP functions in PHP

24 October, 2007 (16:52) | PHP Basics, FTP | By: passion@php

Introduction

FTP is abbreviation for ‘File Transfer Protocol’. The FTP functions in PHP allows an user to connect to and login into a server, creating and removing directories, listing files in the current directory, execute a command, upload and download files to and from the server. It also allows to get and set some runtime options, set a no-blocking option, get a file size, sends a SITE command to the server etc. For this, PHP has standardised set of functions. The FTP functions in PHP were first incorporated in PHP3, later versions have added more to it.

Working with Built in FYP functions in PHP

PHP provides over 34 functions and 10 FTP constants, which together allows you to build robust stand alone PHP based FTP system. In this article, we will consider some of the most used function and see how to use them.

Connecting to a FTP server

The ftp_connect() function opens an FTP connection to a server. While is connection is open you can run other FTP functions.

When the connection is open, you can run FTP functions against the server.

Syntax of this function is: ftp_connect(host, port, timeout)

Where, host is the server name or IP address, port is the port number of connection, by default ftp works in port 21 and timeout is optional it indicates the timeout for the connection with default value 90

<?php
$conn = ftp_connect("ftp.testdomain.com") or die("Could not connect");
?>

Login to an FTP server

After you have connected to a machine, next job will naturally be to log into it. The ftp_login() function allows an user to log in into a server.

Syntax of this function is: ftp_login(ftp_conn,username,password)

Where, ftp_conn is the connection established, username and password is the login username and password.This function returns TRUE on success and FALSE and a warning on failure.

<?php
$conn = ftp_connect("ftp.testdomain.com") or die("Could not connect");
ftp_login($conn,"admin","pass123");
ftp_close($conn);
?>

Retrieving files

You are going to retrieve a file and might not know the filename exactly. Before, retrieving the file you can do some sleuthing. First, let’s retrieve a list of files from a specific directory.

$list = ftp_rawlist($resource, ‘/mydir’);

This will return a raw list of all the files in a directory. Depending on the operating system, a series of information could be returned for each file name. The ftp_systype() function will even show you the OS of the FTP server.

PHP provides the following two file retrieving functions:

  1. ftp_fget() Downloads a file from the FTP server and saves it to an open file.
  2. ftp_get() Downloads a file from the FTP server.

Both the functions take same list of parameters

The syntax :
ftp_fget(ftp_conn,remote,local,mode,resume)

where, remote is a required parameter which specifies the path of the file to copy, local is also a required parameter specifies the path of the open file to paste into and mode is also required parameter specifies the mode of write. It has two values: FTP_ASCII and FTP_BINARY. resume is an optional parameter it specifies the place in the file to start copying, default value is 0 for beginning.

<?php
$source = "source.txt";
$target = fopen("target.txt", "w");
$conn = ftp_connect("ftp.testftp.com") or die("Could not connect");
ftp_login($conn,"admin","pass123");
ftp_fget($conn,$source,$target,FTP_ASCII);
ftp_close($conn);
?>

ftp_get has same syntax: ftp_get(ftp_connection,local,remote,mode,resume)

<?php
$conn = ftp_connect("ftp.testftp.com") or die("Could not connect");
ftp_login($conn,"admin","pass123");
echo ftp_get($conn,"target.txt","source.txt",FTP_ASCII);
ftp_close($conn);
?>

Uploading files

PHP provides the following two file uploading functions:

  1. ftp_fput() uploads from an open file and saves it to a file on the FTP server.
  2. ftp_put()uploads from a local file to the FTP server.

Here again both the functions take same list of parameters.

The syntax: ftp_fput(ftp_conn,remote,local,mode,resume)

The following code shows the use:

<?php
$source = fopen("source.txt","r");
$conn = ftp_connect("ftp.testftp.com") or die("Could not connect");
ftp_login($conn,"admin","pass123");
echo ftp_fput($conn,"target.txt",$source,FTP_ASCII);
ftp_close($conn);
?>

For uploading a local file the ftp_put() function is used:

<?php
$conn = ftp_connect("ftp.testftp.com") or die("Could not connect");
ftp_login($conn,"admin","pass123");
echo ftp_put($conn,"target.txt","source.txt",FTP_ASCII);
ftp_close($conn);
?>

So now you know the basic ftp functions. You must not forget to close the connection once your job is done.