Newsletter: Buy discount phentermine Bromocriptine Meridia Vinorelbine Viagra vs levivia Order viagra now Cheap phentermine prescription Buy generic viagra Any drug interaction xanax and cold meds Natural over counter just like viagra stores Ambien 10mg Albendazole Cialis viagra levivia Mechlorethamine Xanax liver damage Viagra alternative and woman Buy buy domain link online online viagra info viag Generic tramadol Cheap tramadol 180 Crohns phentermine Cheapest cialis price Levivia viagra compared Tramadol drug interactions Tramadol online Viagra overnight Lotrimin Free generic viagra samples Meclofenamate Phenytoin Buy cheap viagra Ways to inject xanax pills Luvox Watson soma Hyperalimentation Viagra drug interaction Viagra alternatives Paris france cheep viagra Cheap xanax online Piperacillin Soma restaurant Tramadol abuse Phentermine price Viagra online canada Buy online tramadol Injecting phentermine Viagra buy viagra Online doctors perscriptions xanax steroids Viagra sale uk Viagra substitute Depakote Cheap phentermine 37.5 mg Viagra paypal france Divalproex Buy cialis generic online Hydrocodone online pharmacy Phentermine 37.5 mg diet pill Tramadol saturday delivery Piperacetazine Pyrazinamide Can xanax cause frontal lobe dementia Mexiletine Buy cheap domain onlineoutdoorscom xanax Order phentermine online without perscription Anileridine Lamotrigine Cialis soft tabs Soma financial Phentermine international order Mycostatin Viagra lawsuits Zithromax Filing income tax buy tramadol Tramadol uses Fluphenazine Tramadol used for Bexarotene Viagra versand Discounted phentermine with no prescription Lethal dose of xanax Iproniazid Combivent Keppra Free viagra prescription Comparison viagra cialis levivia Caffeine Phensuximide Phentermine resident sale virginia Femara Amitriptyline Phentermine & health risks Phentermine diet pills Viagra cialis levivia dose comparison Cheapest xanax online Purchase viagra on line Propofol Isosorbide Methaqualone Diphenadione Buy in phentermine uk Free shipping with phentermine order Phentermine prices Aprotinin Indocin Order phentermine phentermine online Glucophage Chinese viagra dragon power Cheap xanax Generic sample viagra Buy generic online phentermine Terbinafine Cardizem Phentermine free consultation Quinapril Buy phentermine online without a prescription Azatadine Adipex cheap phentermine Why phentermine Phentermine florida Purchase soma Cheep phentermine Ganciclovir Tramadol dosage Natural alternative viagra Smoking xanax Does phentermine speed up metabolism No overnight prescription xanax How do i stop taking phentermine Xanax prescription online Lisinopril Online viagra sale Phentermine 15 mgs Triprolidine Miconazole Acyclovir Diet information phentermine pill Buy viagra online get prescription Viagra dangers Estrogen Viagra in woman Effects of phentermine Buy phentermine tablet Purchase hydrocodone About xanax Cheap phentermine cod Phentermine no prescription required next day delivery Viagra alternates Colon cleanse ambien Viagra online Avandamet Cyclophosphamide Buy online salescom viagra Thiphenamil Inject xanax Viagra dose Compare phentermine price Buy generic viagra online Phentermine pharmacy Nadolol Phentermine ship to ky Calcitriol Cheap phentermine no prescription Permax Mail order viagra Tramadol hcl acetaminotran par Cialis lowest price Drug screen xanax Cheap viagra online Phentermine cheap Diet drug loss phentermine weight Cod free phentermine shipping Lotrimin Mexican pharmacies online+xanax Iothalamate Lamisil Sucralfate Methylphenidate Yohimbe and viagra Womans viagra Herbal substitute viagra Lowest price viagra Cheap phentermine pills Lowest cost phentermine guarantee free shipping Viagra cialis Picture of soma Methadone xanax interaction Viagra like pill How much xanax is a lethal dose Naprosyn Ibutilide Phentermine 37.5 mg free shipping Pravachol Akane soma Linezolid Generic xanax online Buy get online prescription viagra Cialis generic canada Anxiety disorder xanax Tramadol dogs Kanamycin Adipex p phentermine vs Compare viagra prices Phentermine airborne express+cod Guanfacine Lowest price phentermine Fioricet information Buy cialis in uk Viagra and ischemic optic neuropathy Xanax paypal Drug test tramadol hydochloride Cerivastatin Niacinamide Picture of xanax pill Veterinary use of tramadol Cope Nystatin Diet free phentermine pill shipping Generic vicodin Avalide Phentermine free online consultation Pay pal phentermine Isotretinoin Buy ambien online Amikacin Esmolol Drug interactions tramadol elavil Cortisone Benztropine Tramadol prescription Different types of phentermine Procainamide Paregoric Online viagra sales History of phentermine use Warfarin Discount phentermine free shipping Phendimetrazine Cialis story Cialis no prescription Phentermine and methamphetamine Will xanax help me sleep while on adderall Canada xanax Nitroglycerin and viagra Compare viagra cialis levivia Herbal phentermine Adipexdrug addiction order phentermine online Atacand 180 tramadol Atenolol Amiloride Buy phentermine online Loxapine Phentermine quick Cheep tramadol paris france Xanax overnight Gabapentin Aricept Prinivil Picture of xanax pills Ciprofloxacin Epo Tramadol drug Probenecid Phentermine blogging Overdose xanax Cialis sample Levlen Xanax mexico Phentermine fastin Guaifenesin Phentermine no prescription needed Cymbalta Add a link viagra Us phentermine Phentermine line No perscription tramadol Discount hydrocodone Repaglinide Fioricet with codeine Viagra picture Purchase tramadol without a prescription Diamox Naproxen Phentermine pill town Tolazamide Acetyldigitoxin Oxyphenbutazone Phentermine prescription online Isoproterenol Xanax medication Phentermine $70 no prescription Phentermine us pharmacy online consultation Cialis company Pentamidine Meridia weight loss pill Fioricet line Mark martin uniform jacket team caliber viagra Famvir Brompheniramine Phentermine warning Hydrocodone withdrawal Acitretin Doxycycline Flagyl Diet pill xanax Xanax ambien Next day phentermine Buy cheap tramadol Tamoxifen Phentermine delivered overnight Oxycontin xanax bars perclesept and lortab wha Adipex diet phentermine pill prescription Feldene 0 buy by popl powered viagra wordpress Phentermine buy order Viagra cialis levitra comparison dosages Ceftin Viagra for sale Pharmacy phentermine sister Furosemide Hydrocodone cod Quinethazone Cheap perscription phentermine Celexa Order phentermine online Can i buy phentermine anywhere in uk Thiabendazole Advair Herbal phentermine forum Tools needed for injecting xanax Viagra recreational Phentermine amide Amsterdam holland viagra Effects of long term xanax use Generic viagra fast shipping Premphase Purchase xanax Vicodin and alcohol Sell viagra online Dihydrotachysterol Dont buy on black market get viagra legally Soma sleep Order viagra without prescription Discount viagra europe Cetirizine Soma online pharmacy Atenolol Nabumetone Viagra cialis generic Olanzapine Procarbazine Can i take xanax with zocor and procardia Montelukast Phentermine 37.5 in round white tablets no imprint code Lipids Discount phentermine price Does phentermine interact with hydrocodone Arthrotec Cialis prescriptions Phentermine prescription diet pill Chlorotrianisene Buy cod diet phentermine pill Civiate generic sildenafil viagra Vicodin and pregnancy Restoril Cilostazol Hydrochlorothiazide Hydrocodone drug Phentermine addiction help Dog xanax Keflex Inexpensive viagra Leucovorin Loprox Encainide Cialis Xanax no rx Chlorprothixene Info on meridia Is phentermine addictive Cialis price comparison Phentermine fda Asa 50mg viagra Cialis dosage Cafergot Prescriptions on line phentermine Pentasa 2mg xanax Viagra use Online pharmacy and phentermine overnight Buspar Pfizer viagra sperm Xanax indications Buy online phentermine shipping Tramadol medicine Tramadol cheap overnight inexpensive Buying viagra on line Paxil and xanax interaction Cialis levivia sales viagra Sotalol Tramadol hydrochloride tablets Podofilox Sulindac Prescription viagra written Oxycontin xanax bars percasettes and lor tabs Phentermine online without a prescription Phentermine 37.5 mg Cefazolin Nicoumalone Tramadol ultram Diet no phentermine pill prescription Encare Ambien withdrawal Micronase Triazolam Citalopram Glycopyrrolate Phentermine a159 Alka seltzer Cialis order Hydroxyzine Phentermine online diet pill Cheap tramadol prescriptions online Xanax 0.25 mg

Entries Comments



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.