PHP Interview Questions With Answers
PHP Interview Questions With Answers
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.';
?>
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.';
?>
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.";
?>
<?php
$variable = "and";
echo "part 1 $variable part 2\n";
echo "part 1 ".$variable." part 2\n";
?>
• "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 (}).
<?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";
?>
• "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.
<?php
$fruits = array('strawberry' => 'red', 'banana' => 'yellow');
echo "A banana is $fruits[banana].\n";
echo "A banana is {$fruits['banana']}.\n";
?>
A banana is yellow.
A banana is yellow.
<?php
$string = 'It\'s Friday!';
echo "The first character is $string{0}\n";
echo "The first character is {$string{0}}\n";
?>
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";
?>
It's Friday?
It's Friday!
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";
?>
Hello world!
<?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");
}
?>
$a > $b is true.
$a == $b is false.
$a < $b is false.
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 . "\n");
print(1 . " + " . 2 . " = " . 1+2 . "\n");
print(1 . " + " . 2 . " = " . (1+2) . "\n");
print(1 . " + " . 2 . " = 3\n");
print("\n");
?>
-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.
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.
<?php
$foo = 1 + "10.5";
echo "\$foo=$foo; type is " . gettype ($foo) . "\n";
$foo = 1 + "-1.3e3";
echo "\$foo=$foo; type is " . gettype ($foo) . "\n";
$foo = 1 + "bob-1.3e3";
echo "\$foo=$foo; type is " . gettype ($foo) . "\n";
$foo = 1 + "bob3";
echo "\$foo=$foo; type is " . gettype ($foo) . "\n";
$foo = 1 + "10 Small Pigs";
echo "\$foo=$foo; type is " . gettype ($foo) . "\n";
$foo = 4 + "10.2 Little Piggies";
echo "\$foo=$foo; type is " . gettype ($foo) . "\n";
$foo = "10.0 pigs " + 1;
echo "\$foo=$foo; type is " . gettype ($foo) . "\n";
$foo = "10.0 pigs " + 1.0;
echo "\$foo=$foo; type is " . gettype ($foo) . "\n";
?>
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!'));
?>
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().
<?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");
?>
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...
?>
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:
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");
}
?>
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");
?>
substr() can take negative starting position counted from the end of the 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");
?>
Like substr(), substr_replace() can take negative starting position counted from the end of
the string.
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");
?>
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");
?>
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");
?>
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");
?>
strcmp($a, $b): 1
strcmp($b, $a): -1
strcmp($a, $a): 0
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");
?>
Hello world!
48656c6c6f09776f726c64210a
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");
?>
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");
?>
72
H
There are two functions you can use to split a string into pieces:
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);
?>
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 ".".
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");
?>
<?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");
}
?>
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.
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".
<?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");
?>
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?
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.
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");
Empty array:
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");
?>
Test 1: 1
Test 2: 1
Test 3:
Test 4:
Test 5:
Test 6:
You can retrieve values out of arrays using the array element expression $array[$key].
Here is a PHP example script:
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");
?>
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:
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.
<?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);
?>
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");
?>
$newArray["One"] = Python
$oldArray["One"] = Perl
$refArray["Two"] = C#
$oldArray["Two"] = C#
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.
<?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");
}
?>
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);
?>
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 2 uses the array returned by the split() function. Test 3 shows that list() will ignore
any values with string keys.
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");
?>
Size 1: 3
Size 2: 0
There are two functions can be used to test if a key is defined in an array or not:
<?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");
?>
Is 'One' defined? 1
Is '1' defined?
Is 'Two' defined? 1
Is '2' defined?
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.
<?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");
?>
Search 1: 1
Search 2: 0
Search 3:
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);
?>
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);
?>
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);
?>
Sorted by keys:
Array
(
[] => Basic
[Two] => Java
[Zero] => PHP
[1] => Perl
[3] => C+
[4] => Pascal
[5] => FORTRAN
)
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);
?>
Sorted by values:
Array
(
[0] => Basic
[1] => C+
[2] => FORTRAN
[3] => Java
[4] => PHP
[5] => Pascal
[6] => Perl
)
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");
?>
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
)
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);
?>
Merged:
Array
(
[0] => Perl
[1] => PHP
[2] => Java
[i] => Windows
[ii] => Unix
[iii] => Mac
)
A queue is a simple data structure that manages data elements following the first-in-first-
out 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.
<?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);
?>
A stack is a simple data structure that manages data elements following the first-in-last-
out 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.
<?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);
?>
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");
?>
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");
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");
?>
Integers:
Array
(
[0] => 1
[1] => 4
[2] => 7
[3] => 10
[4] => 13
[5] => 16
[6] => 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.
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");
?>
Padded:
---,---,PHP,Perl,Java,>>,>>,>>
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);
?>
Remaining chunk:
Array
(
[Zero] => PHP
)
Removed chunk:
Array
(
[One] => Perl
[Two] => Java
)
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");
?>
There are two functions you can use to split a string into an Array of Substring:
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);
?>
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 ".".
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");
?>
Minimum number: 1
Maximum number: 7
Minimum string: Java
Maximum string: 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();
?>
Hello world!
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");
?>
Hello Bob!
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");
?>
<?php
function f2c($f) {
return ($f - 32.0)/1.8;
}
print("Celsius: ".f2c(100.0)."\n");
print("Celsius: ".f2c(-40.0)."\n");
?>
Celsius: 37.777777777778
Celsius: -40
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");
?>
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");
?>
Note that call-time pass-by-reference has been deprecated. You need to define arguments
as references. See next tip for details.
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");
?>
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");
?>
Average: 3.75
<?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");
?>
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");
?>
Note that call-time pass-by-reference has been deprecated. You need to define arguments
as references. See next tip for details.
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");
?>
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");
?>
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");
?>
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");
?>
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");
?>
<?php
$favor = "vbulletin";
function getFavor() {
global $favor;
return $favor;
}
$myFavor = getFavor();
print("Favorite tool: $myFavor\n");
$favor = "phpbb";
print("Favorite tool: $myFavor\n");
?>
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?
<?php
$favor = "vbulletin";
function &getFavorRef() {
global $favor;
return $favor;
}
$myFavor = &getFavorRef();
print("Favorite tool: $myFavor\n");
$favor = "phpbb";
print("Favorite tool: $myFavor\n");
?>
As you can see, changing the value in $favor does affect $myFavor, because $myFavor is
a reference to $favor.
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");
?>
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:
<?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");
?>
Average 1: 109.33333333333
Average 2: 107.66666666667
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...
}
?>
echo 7/tcp
ftp 21/tcp
telnet 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".
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");
?>
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);
?>
Note that you should always call fclose() to close the opened file when you are done with
the file.
<?php
$file = fopen("/temp/todo.txt", "w");
fwrite($file,"Download PHP scripts at dev.pickzycenter.com.\r\n");
fclose($file);
?>
Note that you should use "\r\n" to terminate lines on Windows. On a Unix system, you
should use "\n".
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);
?>
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.
<?php
$file = fopen("/windows/system32/drivers/etc/services", "r");
while ( ($line=fgets($file)) !== false ) {
$line = rtrim($line);
print("$line\n");
# more statements...
}
fclose($file);
?>
echo 7/tcp
ftp 21/tcp
telnet 23/tcp
smtp 25/tcp
...
Note that rtrim() is used to remove "\n" from the returning string of fgets().
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");
?>
Number of /: 113
Note that rtrim() is used to remove "\n" from the returning string of fgets().
<?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);
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:
<?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 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.
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);
?>
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");
?>
<?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");
?>
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);
?>
"!" 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.
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);
?>
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.
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");
}
?>
Directory created.
If you run this script again, it will print:
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");
}
?>
Directory removed.
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");
}
?>
File removed.
<?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");
}
?>
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);
?>
Array
(
[0] => .
[1] => ..
[2] => todo.txt
)
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);
?>
List of files:
.
..
todo.txt
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");
?>
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
)
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:
Where "processing.php" specifies the PHP page that processes the submitted data in the
form.
HTML tags that can be used in a form to collect input data are:
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.
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.
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");
?>
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:
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");
?>
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.
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:
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.
• 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.
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.
<?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");
?>
<?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.
If you want to provide a default value to a text field in your form, you need to pay
attention to following notes:
<?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.
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! :->"
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.
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.
<?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
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 =
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");
?>
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! :->"
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().
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".
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");
?>
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";
}
?>
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");
?>
"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:
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");
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");
?>
Close your browser and open it again to the same page. You will see:
This proves that "CouponNumber" and CouponValue" persisted outside the browser.
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");
?>
• 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.
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");
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
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: */*
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:
Check the cookie directory again. All cookie files should be deleted.
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.
<?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:
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
*
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.
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:
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:
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:
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:
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:
Keep clicking the refresh button, you will see the limit of your browser.
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.
<?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");
?>
>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.
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:
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.
The session support can be turned on automatically at the site level, or manually in each
PHP page script:
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");
If you save this script to your Web server as first_page.php and visit it with a browser,
you will get:
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:
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.
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:
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:
Now you know that the session ID created by the PHP engine is 26 characters long with
alphanumeric characters only.
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:
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:
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? 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.
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.
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.
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:
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:
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).
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:
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:
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:
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');
}
}
?>
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:
<?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.
• 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
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. Commands end with ; or \g.
mysql> quit;
Bye
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:
If you want access the MySQL server, you must create a connection object first by calling
the mysql_connect() function in the following format:
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
<?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");
}
If you run this script, you will get something like this:
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.
<?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";
mysql_close($con);
?>
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:
Here is a good example of running a SQL statement with the mysql_query() function:
<?php
include "mysql_connection.php";
mysql_close($con);
?>
If you run this script, you will get something like this:
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";
mysql_close($con);
?>
There are two functions you can use the get the number of rows selected or affected by a
SQL statement:
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";
mysql_close($con);
?>
1 rows inserted.
1 rows inserted.
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";
mysql_close($con);
?>
If you run this script, you will get something like this:
2 rows inserted.
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";
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:
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";
If you run this script, you will get something like this:
1 rows updated.
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";
mysql_close($con);
?>
If you run this script, you will get something like this:
1 rows deleted.
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";
mysql_close($con);
?>
If you run this script, you will get something like this:
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";
mysql_close($con);
?>
If you run this script, you will get something like this:
1 rows inserted.
1 rows inserted.
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:
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);
?>
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";
mysql_close($con);
?>
If you run this script, a new table will be created with ID column defined as auto-
increment. 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
<?php
include "mysql_connection.php";
mysql_close($con);
?>
If you run this script, you will get something like this:
1 rows inserted.
Last ID inserted: 3
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:
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.
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:
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");
?>
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:
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.
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 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:
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.
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");
?>
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);
?>
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.
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.