Beruflich Dokumente
Kultur Dokumente
When a user navigates in her browser to a page that ends with a .php extension, the request is sent to a web server, which directs the request to the PHP interpreter.
As shown in the diagram above, the PHP interpreter processes the page, communicating with file systems, databases, and email servers as necessary, and then delivers a web page to the web server to return to the browser.
This is the most commonly used (and recommended) form. It is known as the XML style, because it can be used inside of an XML document without causing the document to become poorly formed. HTML or Script style tags.
language="php"> PHP CODE GOES IN HERE </script> <? PHP CODE GOES HERE ?> <% PHP CODE GOES HERE %>
In this manual, we will use the first form shown as it is the most common and the most portable.
Comments
PHP has two forms of comments:
Syntax
Single-line comments begin with a double slash (//). Multi-line comments begin with "/*" and end with "*/".
PHP Functions
There are literally hundreds of built-in PHP functions that do everything from returning the current date and time on the server to pulling data out of a database. A function might take zero arguments (e.g, phpinfo(), which returns information on the PHP environment) or it might take several arguments (e.g, mail(), which takes three required and two optional arguments). The syntax for calling a function is straightforward: Syntax
function_name(arguments);
Introduction to php.net
PHP functions are well documented at http://www.php.net. You can quickly look up documentation on a function by going to http://www.php.net/function_name. For example, to see documentation on phpinfo(), go to http://www.php.net/phpinfo. (see footnote)
Hello World!
It is an unwritten rule that every programming course must contain a "Hello World!" script. Here it is:
Code between <?php and ?> is processed by the PHP interpreter. The echo command is used to print text back to the browser.
This code isn't very exciting. In fact, PHP doesn't buy us anything here as we could have just as easily output the result using straight HTML. There is nothing dynamic about this script. After learning about variables, we'll take a look at some more interesting examples.
Variables
PHP variables begin with a dollar sign ($) as shown below. Syntax
$var_name = "Value";
Variable Types
Variable Type Integer Double String Boolean Array Object Explanation whole number real number string of characters true or false list of items instance of a class
Type Strength
PHP is weakly typed, meaning that variables do not need to be assigned a type (e.g, Integer) at the time they are declared. Rather, the type of a PHP variable is determined by the value the variable holds and the way in which it is used.
Hello Variables!
Here is the "Hello World!" script again, but this time we use a variable.
Code Explanation This time the string "Hello World!" is stored in the $Greeting variable, which is output in the title and body of the page with an echo command.
4.
Test your solution in a browser. The resulting HTML page should look like this:
Instead of assigning a literal string (e.g, "Monday") to $Today, use the built-in date() function so that the script won't have to be manually updated every day to stay current. For documentation, visit http://www.php.net/date. Where is the solution?
Variable Scope
A variable's scope determines the locations from which the variable can be accessed. PHP variables are either superglobal, global, or local. Variable Scope superglobal global function
Explanation Superglobal variables are predefined arrays, including $_POST and $_GET. They are accessible from anywhere on the page. Global variables are visible throughout the script in which they are declared. However, they are not visible within functions in the script unless they are re-declared within the function as global variables. Variables in the function scope are called local variables. Local variables are local to the function in which they are declared.
Superglobals
Again, superglobal variables are predefined arrays, including $_POST and $_GET and are accessible from anywhere on the page. The complete list of superglobals is shown below.
$_GET - variables passed into a page on the query string. $_POST - variables passed into a page through a form using the post method. $_SERVER - server environment variables (e.g, $_SERVER['HTTP_REFERER'] returns the URL of the referring page). $_COOKIE - cookie variables. $_FILES - variables containing information about uploaded files. $_ENV - PHP environment variables (e.g, $_ENV['HTTP_HOST'] returns the name of the host server. (see footnote) $_REQUEST - variables passed into a page through forms, the query string and cookies. $_SESSION - session variables.
The elements within superglobal variables can be accessed in three different ways, which the authors of PHP and MySQL Web Development refer to as short style, medium style, and long style. (see footnote) Style Syntax (using $_GET) Notes
Short $varname
Convenient, but it makes it difficult to distinguish superglobal variables from other variables in the code. Requires register_globals config setting to be on. Recommended approach. Happy medium between convenience and clarity. Not available before v. 4.1. Inconvenient to type. Deprecated, but still supported in current versions. Can be disabled via the register_long_arrays directive in the php.ini file.
Medium $_GET['varname']
Long
$HTTP_GET_VARS['varname']
Constants
Constants are like variables except that, once assigned a value, they cannot be changed. Constants are created using the define() function and by convention (but not by rule) are in all uppercase letters. Constants can be accessed from anywhere on the page. Syntax
define('CONST_NAME',VALUE);
PHP Operators
Operators in PHP are similar to those found in many modern C-like programming languages. Mathematical Operators Operator
+ * / %
Operator
.
Name Concatenation
Example
$a . $b 'Hello' . ' world!'
Name Assignment
$a $a $a $a $a $a += -= *= /= %= .=
Example
$a = 1; $c = 'Hello' . ' world!'; 1; 1; 2; 2; 2; ' world!';
Combination Assignment
Example
$foo = ($age >= 18) ? 'adult' : 'child'; $a = @(1/0);
Because of the use of single quotes above, the string "\tHello\n$person!!" will be output literally, as shown below.
This time, because of the double quotes, the string will be parsed for variables and special characters and will be output as shown
below. To see the effect of the special characters (\n and \t), you will have to view the source of the resulting page.
The part of the URL that follows the question mark is called the query string. One or more name-value pairs can be passed to the server in this way. Each name-value pair is separated by an ampersand (&). The processing page can read these name-value pairs and use them to determine its response. The HTML page below shows an example of how these name-value pairs might be passed.
$greeting = $_GET['greet']; ?> <html> <head> <title><?= $greeting ?> World!</title> </head> <body> <?php echo "$greeting World!"; ?> </body> </html>
Variable names begin with a dollar sign ($). Values passed in the query string are part of the $_GET array and can be accessed using the following syntax: $_GET['fieldname']. A shortcut for echo 'text to print'; is <?= 'text to print' ?>. (see footnote)
Change the links so that each Beatle gets a custom greeting (e.g, Howdy Paul, Hi John, Bye George, Hey Ringo). Where is the solution?
Conditional Processing
Conditional processing allows programmers to output different code based on specific conditions. There are two conditional structures in PHP - if-elseif-else and switch/case.
If Conditions
Simple if statement
Syntax
if (conditions) Do this;
10
In the above code, the Do this; statement will either run or not run depending on whether or not the conditions are true. This syntax can only be used when the condition affects a single line of code. For a block of code, use the following syntax. Syntax
if (conditions) { Do this; Then do this; And this too; }
The lines of code affected by the if condition are put in a code block, which is surrounded by curly brackets to indicate that all of the code either should or should not be executed, depending on the result of the if condition.
if-else statement
Syntax
if (conditions) { Do this; } else { Do that; }
if-elseif-else statement
Syntax
if (conditions) { Do this; } elseif (other conditions) { Do that; } else { Do this other thing; }
The two syntax blocks above show an if-else and an if-elseif-else statement, which can have any number of elseif blocks. The following table shows PHP's comparison operators. Comparison Operators Operator == != > < >= <= === !== Description Equals Doesn't equal Is greater than Is less than Is greater than or equal to Is less than or equal to Identical (same value and same type) Not Identical
<html> <head> <title>if-elseif-else</title> </head> <body> <?php $Age = 21; if ($Age >= 21) { echo 'You can vote and drink!'; } elseif ($Age >= 18) { echo 'You can vote, but can\'t drink.'; } else { echo 'You cannot vote or drink.'; } ?> </body> </html>
Code Explanation The file is relatively simple. You can see the different results by changing the value of $Age.
Compound If Statements
More complex if statements often require that several conditions be checked. The table below shows and and or operators for checking multiple conditions and the not operator for negating a boolean value (i.e, turning true to false or vice versa). Logical Operators Operator Name Example && AND $a && $b || OR $a || $b ! NOT !$b The following example shows these logical operators in practice.
12
switch/case
A switch/case statement is similar to an if statement, except that it can only check for an equality comparison of a single expression. It cannot, for example, be used to check if one value is higher than another. Syntax
switch (expression) { case 'a' : echo 'expression is break; case 'b' : echo 'expression is break; case 'c' : echo 'expression is break; default : echo 'expression is break; }
The break statement is important. Without it, after a single match is found, all following statements will execute. The following example demonstrates a switch/case statement without break statements.
Code Explanation
13
Notice that, once a match is found, all remaining echo statements are output. The following example shows how this can be fixed by adding break statements.
Code Explanation
14
2. 3.
4. 5.
This form is submitted using the get method (see footnote), which means the form entries will be appended to the query string and will be accessible in the $_GET array. Open FlowControl/Exercises/Greeting.php in your editor. Insert a PHP block that checks to see if the user filled out both the LastName and the Gender fields in the form. o If the user failed to fill out either one of the fields, write out an error message to the screen. o If the user filled out both fields, return a gender-appropriate greeting such as "Hello Mr. Dunn!" or "Hello Ms. Dunn!" If the gender is not recognizable (e.g, not male or female), return an error message. Try to use both an if condition and a switch statement in this exercise. When you are done, test your solution in your browser.
15
It is likely that your solution does not take into account different cases for the gender. For example, "MALE" and "FEMALE" may not be recognized as valid genders. Try to find the function at http://www.php.net that can be used for converting the user's entry to all lowercase letters and use that function to make the gender check case insensitive. Where is the solution?
Loops
As the name implies, loops are used to loop (or iterate) over code blocks. The following section shows the syntax for different types of loops. Each loop will return "12345". There are several types of loops in PHP.
while
while loops are used to execute a block of code repeatedly while one or more conditions is true. Syntax
$a=1; while ($a < 6) { echo $a; $a++; }
do...while
do...while loops are used to execute a block of code repeatedly until one or more conditions is found to be false. The difference between while loops and do...while loops is that the condition is checked after the code block is executed. This means that, in a do...while loop, the code block will always be executed at least once. Syntax
$a=1; do { echo $a; $a++; } while ($a < 6);
for
A for loop takes three expressions separated by semi-colons and grouped in parentheses before the block to be iterated through. 1. 2. 3. The first expression is executed once before the loop starts. It is usually used to initialize the conditions. The second expression is evaluated before each iteration through the loop. If it evaluates to false, the loop ends. The third expression is executed at the end of each iteration through the loop. It is usually used to make changes that can affect the second expression.
Syntax
for ($a=1; $a < 6; $a++) { echo $a;
16
To jump to the next iteration of a loop without executing the remaining statements in the block, insert a continue statement. Syntax
for ($a=1; $a < 6; $a++) { if ($a == 3) { continue; } echo $a; }
In both loops, skip all numbers that are divisible by 3. Be careful not to get caught in an infinite loop. Where is the solution?
Footnotes
1. 2. HTML forms will be discussed more later in the course. foreach loops will be covered in the Arrays lesson.
Indexed Arrays
Indexed arrays are similar to tables with a single column. An indexed array can contain zero or more elements. In PHP, like in many programming languages, the first element of an array is in the "zeroeth" position. An array with no elements has a zero length.
17
Initializing Arrays
Arrays are initialized with the array() function, which can take a list of comma-delimited values that become the elements in the new array. The following lines of code initializes a zero-length array and then adds four elements to the array. Syntax
$Beatles = array(); $Beatles[0] = 'John'; $Beatles[1] = 'Paul'; $Beatles[2] = 'George'; $Beatles[3] = 'Ringo';
The first line above is actually optional as the second line will create the array if one does not already exist. However, it is a better coding practice to explicitly initialize the array. The $Beatles array could also be created in a single line as follows. Syntax
$Beatles = array('John','Paul','George','Ringo');
Appending to an Array
If you know how many elements are in an array, you can append to the array by specifying the index. For example, you could append to the $Beatles array shown above as follows: Syntax
$Beatles[5] = 'Nat';
However, sometimes you don't know how many elements are in an array. Although you can easily figure this out, doing so requires an extra step. PHP provides an easy way of appending to an array of any length. Simply leave out the index. Syntax
$Beatles[] = 'Nat';
18
<h1>Indexed Arrays</h1> <?php $Beatles = array(); $Beatles[0] = 'John'; $Beatles[1] = 'Paul'; $Beatles[2] = 'George'; $Beatles[3] = 'Ringo'; echo $Beatles[2]; //outputs George to the browser $Beatles[] = 'Nat'; ?> <hr/> <?php foreach ($Beatles as $Beatle) { echo "$Beatle<br/>"; } ?> </body> </html>
1. 2. 3. 4.
Open Arrays/Exercises/ColorTable.php for editing. Create an array that holds your favorite colors. Inside of the open and close <table> tags, loop through the array outputting a table row for each element. Test your solution in a browser.
Associative Arrays
19
Whereas indexed arrays are indexed numerically, associative arrays are indexed using names. For example, instead of Ringo being indexed as 3, he could be indexed as "drummer".
20
Superglobal Arrays
The superglobal arrays are associative arrays. The file below outputs all the contents of the superglobal arrays using foreach loops.
21
echo "<li><b>$key:</b> $item<br/></li>"; } ?> </ol> <hr/> <h2>$_SESSION</h2> <ol> <?php foreach ($_SESSION as $key => $item) { echo "<li><b>$key:</b> $item<br/></li>"; } ?> </ol> <hr/> <h2>$_SERVER</h2> <ol> <?php foreach ($_SERVER as $key => $item) { echo "<li><b>$key:</b> $item<br/></li>"; } ?> </ol> </body> </html>
Don't worry about the session_start() statement at the top. We'll cover that in detail later in the course.
22
2. 3. 4.
Create an associative array that holds color hex codes indexed by their color names, which can be found at http://www.w3schools.com/html/html_colornames.asp. After the existing table row, write code to loop through the array outputting a table row with two columns for each element in the array. Test your solution in a browser.
Two-dimensional Arrays
In PHP, two-dimensional arrays are arrays that contain arrays. You can think of the outer array as containing the rows and the inner arrays as containing the data cells in those rows. For example, a two-dimensional array called $Rockbands could contain the names of the bands and some of the songs that they sing. Below is a grid that represents such a two-dimensional array. Rockband Song1 Song2 Song3 Beatles Love Me Do Hey Jude Helter Skelter Rolling Stones Waiting on a Friend Angie Yesterday's Papers Eagles Life in the Fast Lane Hotel California Best of My Love The following code creates this two-dimensional array. The internal arrays are highlighted. Note that the header row is not included. Syntax
$Rockbands = array( array('Beatles','Love Me Do', 'Hey Jude','Helter Skelter'), array('Rolling Stones','Waiting on a Friend','Angie', 'Yesterday\'s Papers'), array('Eagles','Life in the Fast Lane','Hotel California', 'Best of My Love') )
The above code snippets are combined in the following example to output a Rockbands table.
<html> <head> <title>Two-dimensional Arrays</title> </head> <body> <h1>Two-Dimensional Arrays</h1> <?php $Rockbands = array( array('Beatles','Love Me Do', 'Hey Jude','Helter Skelter'), array('Rolling Stones','Waiting on a Friend','Angie','Yesterday\'s Papers'), array('Eagles','Life in the Fast Lane','Hotel California','Best of My Love') ); ?> <table border="1"> <tr> <th>Rockband</th> <th>Song 1</th> <th>Song 2</th> <th>Song 3</th> </tr> <?php foreach($Rockbands as $Rockband) { echo '<tr>'; foreach($Rockband as $item) { echo "<td>$item</td>"; } echo '</tr>'; } ?> </table> </body> </html>
Arrays Conclusion
Arrays are an important feature of many modern programming languages. In this lesson, we have covered the most common uses of arrays.
24
Footnotes
1. 2. 3. See http://www.w3schools.com/html/html_colornames.asp for a list of color names. Remember that the first row is row 0 and the first column is column 0. For a complete list of array functions, see http://www.php.net/array.
HTML Forms
How HTML Forms Work
A very common way to pass data from one page to another is through HTML forms. There are two methods of submitting data through a form: the get method and the post method. The method used is determined by the value of the method attribute of the form tag. The default method is get.
Get Method
When the get method is used, data is sent to the server in name-value pairs as part of the query string. The get method is most commonly used by search pages and is useful when it is important to be able to bookmark the resulting page (i.e, the page that is returned after the form is submitted).
Post Method
When the post method is used, data is sent to the server in name-value pairs behind the scenes. The two major advantages of the post method are:
The name-value pairs are not visible in the location bar, so sensitive data such as passwords are not displayed on the screen. Files, such as images and Office documents, can be uploaded via the form.
25
<td> <input type="radio" name="TitleOfCourtesy" value="Dr."/>Dr. <input type="radio" name="TitleOfCourtesy" value="Mr."/>Mr. <input type="radio" name="TitleOfCourtesy" value="Mrs."/>Mrs. <input type="radio" name="TitleOfCourtesy" value="Ms."/>Ms. </td> </tr> <tr> <td>Birth date:</td> <td> <select name="BirthMonth"> <option value="1">January</option> <option value="2">February</option> <option value="3">March</option> <option value="4">April</option> <option value="5">May</option> <option value="6">June</option> <option value="7">July</option> <option value="8">August</option> <option value="9">September</option> <option value="10">October</option> <option value="11">November</option> <option value="12">December</option> </select> <select name="BirthDay"> <?php for ($i=1; $i<=31; $i++) { echo "<option value='$i'>$i</option>"; } ?> </select> <select name="BirthYear"> <?php for ($i=2006; $i>=1900; $i=$i-1) { echo "<option value='$i'>$i</option>"; } ?> </select> </td> </tr> <tr> <td>Hire date:</td> <td> <select name="HireMonth"> <option value="1">January</option> <option value="2">February</option> <option value="3">March</option> <option value="4">April</option> <option value="5">May</option> <option value="6">June</option> <option value="7">July</option> <option value="8">August</option> <option value="9">September</option> <option value="10">October</option> <option value="11">November</option> <option value="12">December</option> </select> <select name="HireDay"> <?php for ($i=1; $i<=31; $i++) { echo "<option value='$i'>$i</option>"; } ?> </select> <select name="HireYear"> <?php for ($i=2006; $i>=1992; $i=$i-1) { echo "<option value='$i'>$i</option>"; } ?> </select> </td> </tr> <tr> <td>Address:</td> <td><input type="text" name="Address" size="50"/></td> </tr>
26
<tr> <td>City:</td> <td><input type="text" name="City" size="30"/></td> </tr> <tr> <td>Region:</td> <td><input type="text" name="Region" size="2"/></td> </tr> <tr> <td>Postal Code:</td> <td><input type="text" name="PostalCode" size="10"/></td> </tr> <tr> <td>Country:</td> <td><input type="text" name="Country" size="5"/></td> </tr> <tr> <td>Home Phone:</td> <td><input type="text" name="HomePhone" size="15"/></td> </tr> <tr> <td>Extension:</td> <td><input type="text" name="Extension" size="5"/></td> </tr> <tr> <td colspan="2">Notes:</td> </tr> <tr> <td colspan="2"> <textarea name="Notes" cols="50" rows="3"></textarea> </td> </tr> <tr> <td>Manager:</td> <td> <select name="ReportsTo"> <option value="0">Choose...</option> <option value="1">Nancy Davolio</option> <option value="2">Andrew Fuller</option> <option value="3">Janet Leverling</option> <option value="4">Margaret Peacock</option> <option value="5">Steven Buchanan</option> <option value="6">Michael Suyama</option> <option value="7">Robert King</option> <option value="8">Laura Callahan</option> <option value="9">Anne Dodsworth</option> </select> </td> </tr> <tr> <td>Password:</td> <td><input type="password" name="Password1" size="10"/></td> </tr> <tr> <td>Repeat Password:</td> <td><input type="password" name="Password2" size="10"/></td> </tr> <tr> <td colspan="2"><input type="submit" value="Add Employee"/></td> </tr> </table> </form> </body> </html>
The above code, which contains some embedded PHP code, outputs a simple HTML form. Its action page is ProcessEmployee.php, which will eventually contain PHP code to process the submitted form.
Form Variables
Form variables are variables that are created when an HTML form is submitted using the post method. These variables are stored in the $_POST superglobal array. Here are a few things you should know about how HTML forms are processed: 1. 2. If a text field or textarea is left blank, the variable is sent to the server with a value of "" (empty string). Select menus always send a variable to the server (unless they have been disabled in some way).
27
3. 4. 5.
If no radio button in a radio array is checked, no variable for that radio array is sent to the server. If a checkbox is not checked, no value is sent to the server. If it is checked, the default value of "on" is sent unless otherwise set in the HTML. If the submit button has a name (e.g, <input type="submit" name="Inserting" value="Add Employee"/>), when that submit button is clicked a variable by that name with the corresponding value will be sent to the server.
28
In this exercise, you will create a page that processes the form data. The form entry page, Exercises/AddEmployee.php, is already complete and is identical to Demos/AddEmployee.php above. Filled out, the form would look like this:
29
30
If all fields are left blank except for the password fields, which contain two different values, the page should display as follows:
1. 2.
3. 4. 5.
Open Forms/Exercises/ProcessEmployee.php in your editor. For each form entry (other than the dates, which we'll worry about later), create a simple global variable to hold... o either an error if the entry is not filled out or filled out incorrectly. o or the value entered. Output the variables as list items as shown in the screenshots above. Save your work. To test your solution, load Forms/Exercises/AddEmployee.php in the browser and fill out and submit the form.
31
//Part of the first one is done for you. echo "<li><b>Name:</b> $FirstName</li>"; ?> </ul> </body> </html>
If there are any errors, include a link at the bottom that directs the user to the form. If there are no errors, include a form full of hidden fields containing the values entered and a submit button that reads "Confirm". Where is the solution?
Formatting Strings
Concatenation
Concatenation is a programming word for adding strings together. In PHP, the concatenation operator is a dot (.). Generally, concatenation is used to combine literal text with variables or values returned from functions. The example below illustrates this.
Code Explanation As shown in the code, double quotes can be used to avoid using the concatenation operator. This works for concatenating literal strings with variables, but it does not work for concatenating values returned from functions. To do that, the function call must be outside of any quotes and combined with the rest of the string using the concatenation operator. This also is demonstrated in the code sample above.
32
Trimming Strings Function Description ltrim() Removes whitespace at the beginning of a string. rtrim() Removes whitespace at the end of a string. Presentation Function htmlentities() nl2br() strtoupper() strtolower() ucfirst() ucwords() Description Escapes all HTML entities. Inserts a <br /> tag before each newline character in a string. Converts a string to uppercase. Converts a string to lowercase. Converts the first character of a string to uppercase. Converts the first character of each word in a string to uppercase. Converting Strings and Arrays Function Description explode() Splits a string into an array on a specified character or group of characters. implode() Converts an array into a string, placing a specified character or group of characters between each array element. join() Same as implode(). Substrings Function substr(str,pos) substr(str,-len) substr(str,pos,len) substr(str,pos,-len) Description Returns the substring from the character in position pos to the end of the string. Returns the substring from len characters from the end of the string to the end of the string. Returns a len length substring beginning with the character in position pos. Returns a substring beginning with the character in position pos and chopping off the last len characters of the string. If the third argument (before_needle) is false (default), then it returns the part of the haystack from the needle on.
strstr(haystack,needle,before_needle) If the third argument (before_needle) is true, then it returns the part of the haystack before the needle. The needle can be a string or an integer (or a number that can be converted to an integer). stristr(haystack,needle,before_needle) Same as strstr(), but case insensitive. Finds the position of the first occurrence of a specified needle in a haystack (string). strpos(haystack,needle) The needle can be a string or an integer (or a number that can be converted to an integer). Finds the position of the last occurrence of a specified needle in a haystack (string). strrpos(haystack,needle) The needle can be a string or an integer (or a number that can be converted to an integer). str_replace() Replaces all occurrences of one string with another string. Comparing Strings Function Description strcmp() Compares two strings. Returns < 0 if str1 is less than str2, > 0 if str1 is greater than str2, and 0 if they are equal. strcasecmp() Like strcmp() but case insensitive. strlen() Returns the length of a string.
33
34
This would result in the JavaScript code being executed. This JavaScript code would create a never-ending loop that popped up an alert over and over again. Although this would be pretty annoying, there are much worse things users could do, such as make a remote procedure call to execute a page on your server. You can test this by opening Strings/Demos/HtmlEntitiesNotUsed.html and submitting the form. You probably don't want to test with a never-ending loop though. This can easily be fixed by changing the code to look like this:
35
This script uses htmlentities() to escape all the HTML entities and uses nl2br() to convert newline characters to breaks. The
resulting output looks like this: And the resulting HTML source looks like this:
<html> <head> <title>HTML Entities Processor</title> </head> <body> <h1>HTML Entities Processor</h1> <script language="javascript"><br /> while (true)<br /> {<br /> alert("Try to get rid of me!");<br /> }<br /> </script></body> </html>
explode()
36
The explode() function is used to convert a string to an array. The following form submits to Explode.php, the code of which is
shown below.
Notice that the trim() function is used to trim the resulting elements of the array. This is because the string is exploded on the semi-colon only. If the user adds additional whitespace around the semi-colon, that whitespace will be part of the array element.
substr()
37
As shown earlier, the substr() function behaves differently depending on the values passed to it. The following screenshot shows
Magic Quotes
There are two settings in the php.ini file that determine how PHP handles incoming data. The settings are magic_quotes_gpc (on by default) and magic_quotes_runtime (off by default).
magic_quotes_gpc
The value of magic_quotes_gpc determines whether GET, POST and COOKIE data should be escaped "automagically". If magic_quotes_gpc is set to 1, then single quotes, double quotes and backslashes will be escaped with backslashes. In this case, if a user entered "O'Reilly" as her last name, and your script returned that value to the browser (e.g, echo $_POST['LastName'];), the value returned would read "O\'Reilly". You would need to strip the backslashes by passing the value through the stripslashes() function (e.g, echo stripslashes($_POST['LastName']);). Although magic quotes can be useful, they can also cause confusion as the developer may not know whether magic quotes are turned on or off. To check whether they are on, use the get_magic_quotes_gpc() function as shown below.
38
magic_quotes_runtime
The value of magic_quotes_runtime determines whether data returned from files and databases should be escaped "automagically". It works similarly to magic_quotes_gpc.
Footnotes
1. Another function called htmlspecialchars() is similar to htmlentities(). The difference is that htmlentities() escapes all HTML entities, while htmlspecialchars() only escapes the most widely used. If you're interested in seeing the difference, take a look at Strings/Demos/EscapingSpecialChars.php.
Including Files
PHP provides two common constructs for including files in web pages: require and include. They are basically the same with one minor difference. require throws a fatal error when it fails; whereas, include only gives a warning. If you need the included file to continue to process the page, you should use require. It is important to keep in mind that a PHP tag cannot start in a calling file and continue in an included file. All PHP code in the included file must be nested in PHP tags.
require
require is not actually a function, but a language construct, so require statements can be written in two ways: Syntax
require(path_to_file); require path_to_file;
require_once
require_once can be used just like require. The difference is that if the included file has already been included by earlier code, it will not be re-included.
39
A Note on Security
If included files are under the web root, they can be accessed just as any other file can. If they have an extension such as inc then the browser may display them as plain text. With other extensions, the browser may attempt to download the file. If the included file is a PHP file and a user navigates to it, the server will try to process the file and may return errors. As a precaution, you may want to place your included files in a directory above or outside of the web root. This will prevent users from accessing the files directly.
include_path directive
The php.ini contains an include_path directive, which takes a semi-colon delimited list of paths to directories that PHP should look in for included files. Here is a code sample that demonstrates how to include files using require.
Code Explanation The above code is relatively straightforward. Require.php contains two included (required) files: Required.php and Required.inc. Notice that there is PHP code inside of Required.inc, which is executed. The extension of the included files does not affect how the code inside the files will be executed.
40
4.
To test your solution, load ReusingCode/Exercises/index.php in the browser. It should display as follows:
The auto_prepend_file directive can be used to application-wide variables such as database connection strings or common file paths. The auto_append_file directive can be used for cleaning up code or for outputting debugging information to the browser. Note that it is not possible to set different auto-prepend and auto-append files for different directories or different scripts.
User Functions
41
User functions are used to make common tasks easier and to make code more modular and easier to read. Unlike other identifiers in PHP, functions are case insensitive.
Like built-in functions, user functions can receive parameters. To define a function with parameters, place receiving variables in the parentheses. Syntax
function addNums($param1, $param2, $param3) { $sum = $param1 + $param2 + $param3; echo 'The sum is ' . $sum; }
User functions are called in the same way that built-in functions are. For example, the following code calls the addNums() function to get the sum of three numbers. Syntax
$total = addNums(1,3,5);
Default Values
You can make function parameters optional by assigning default values to them as shown in the example below.
42
Code Explanation In this case, if you don't pass a value into the function for one or more of the parameters, the default value of 0 will be used. When defining a function, all required parameters should precede optional parameters.
Variable Scope
In PHP, variables declared outside of functions are not available by default inside of functions. The following code illustrates this:
To make the variables available to the function, they must be declared within the function as global variables using the global keyword.
43
The above code outputs "10" to the browser. Although $num was incremented by 5, $a was unaffected by the function call. To pass a variable by reference, put an ampersand (&) before the parameter in the function definition.
This time the function outputs "15" because $num references the variable $a itself. So, any change in $num will affect $a.
Form Processing
Processing forms generally involves the following tasks: 1. 2. 3. 4. Writing the HTML code to output the form. Writing validation code to validate the form entries after the form is submitted. Writing code to output errors if there are any. Writing code to process the form entries if they are all valid.
Although these tasks are all separate, some are dependent on others. For example, if errors are found when the form is submitted, it is nice to re-output the form, but the HTML code may be different from the original form as you will likely want to include error messages and also echo the values that the user entered. It's very easy to get your code all tangled up resulting in what is known as spaghetti code. We will now examine one approach for organizing code using functions and includes to make it easier to maintain.
Code Organization
Application Flow
44
The application we are building works like this: 1. 2. When the user first visits, she is presented with a form to fill out. If she fills out the form... o Correctly She is presented with another form to confirm her entries. After confirming her entries, the data will be processed (e.g, entered into a database or emailed to someone). o Incorrectly She is presented with the same form with her entries in tact and appropriate error messages displayed.
Application Files
To make our code easier to maintain, we will organize it as follows: 1. 2. 3. 4. 5. 6. 7. 8. 9. Includes/init.php - Initializes and sets some variables. AddEmployee.php - Contains code that defines the flow of the application. Includes/EmployeeForm.php - Contains code to display entry form. Includes/ProcessEmployee.php - Contains code to process the original form entry. If there are errors, they will be displayed on the page. If there are no errors, the user's entries will be displayed with a "Confirm" button. Includes/InsertEmployee.php - Contains code to insert the employee into a database. (This file is currently empty.) Includes/fnFormPresentation.php - Contains a library of functions for presenting form fields. Includes/fnFormValidation.php - Contains a library of functions for validating form entries. Includes/fnStrings.php - Contains a couple of useful string functions. Includes/fnDates.php - Contains a useful date function.
45
Code Explanation This file sets several variables used throughout the application.
Code Explanation The code is relatively easy to read. Things to note: 1. 2. At the very top, we include several files we will need for the application. In the body, we include: o our header and footer files. o code that checks which, if either, form was submitted and includes the appropriate file. o code that checks whether or not to show the main form. The form will be shown if: it has not yet been submitted. it has been submitted with errors.
46
$Months[] $Months[] $Months[] $Months[] $Months[] $Months[] $Months[] $Months[] $Months[] $Months[] $Months[]
= = = = = = = = = = =
'February'; 'March'; 'April'; 'May'; 'June'; 'July'; 'August'; 'September'; 'October'; 'November'; 'December';
Code Explanation This file includes a simple function for getting the name of a month (e.g, February) given the month number (e.g, 2).
Code Explanation This file includes functions for cleaning up strings for browser and database output.
47
<input type='text' name='$Name' size='$Size' value=\"" . browserString($Entries[$Name]) . "\">"; if (array_key_exists($Name,$Errors)) { $ReturnVal .= '<span class="Error" style="white-space:nowrap">* ' . $Errors[$Name] . '</span>'; } $ReturnVal .= "</td> </tr>"; return $ReturnVal; } /* Function Name: pwEntry Arguments: $PW1,$PW2,$Errors,$Size? Returns: table rows as string */ function pwEntry($PW1,$PW2,$Errors,$Size=10) { $ReturnVal = " <tr> <td>Password:</td> <td> <input type='password' name='$PW1' size='$Size'> </td> </tr> <tr> <td>Repeat Password:</td> <td> <input type='password' name='$PW2' size='$Size'> </td> </tr>"; if (array_key_exists('Password',$Errors)) { $ReturnVal .= addErrorRow('Password',$Errors); } return $ReturnVal; } /* Function Name: textAreaEntry Arguments: $Display,$Name,$Entries,$Errors,$Cols?,$Rows? Returns: table rows as string */ function textAreaEntry($Display,$Name,$Entries,$Errors,$Cols=45,$Rows=5) { $ReturnVal = " <tr> <td colspan='2'>$Display:</td> </tr> <tr> <td colspan='2'> <textarea name='$Name' cols='$Cols' rows='$Rows'>"; $ReturnVal .= $Entries[$Name]; $ReturnVal .= "</textarea> </td> </tr>"; if (array_key_exists($Name,$Errors)) { $ReturnVal .= addErrorRow($Name,$Errors); } return $ReturnVal; } /* Function Name: radioEntry Arguments: $Display,$Name,$Entries,$Errors,$Values Returns: table rows as string */ function radioEntry($Display,$Name,$Entries,$Errors,$Values) { $ReturnVal = "
48
<tr> <td>$Display:</td> <td>$Name</td> </tr>"; return $ReturnVal; } /* Function Name: selectEntry Arguments: $Display,$Name,$Entries,$Errors,$Selected? Returns: table rows as string */ function selectEntry($Display,$Name,$Options,$Errors,$Selected=0) { $ReturnVal = "<tr> <td>$Display:</td> <td> <select name='$Name'> <option value='0'>Choose one...</option>"; $ReturnVal .= "</select> </td> </tr>"; return $ReturnVal; } /* Function Name: selectDateEntry Arguments: $Display,$NamePre,$Month,$Day,$Year Returns: table rows as string */ function selectDateEntry($Display,$NamePre,$Month,$Day,$Year,$Errors) { $ReturnVal = "<tr> <td>$Display:</td> <td> <select name='$NamePre" . "Month'>"; for ($i=1; $i<=12; $i++) { if ($i == $Month) { $ReturnVal .= "<option value='$i' selected>"; } else { $ReturnVal .= "<option value='$i'>"; } $ReturnVal .= monthAsString($i) . '</option>'; } $ReturnVal .= "</select> <select name='$NamePre" . "Day'>"; for ($i=1; $i<=31; $i++) { if ($i == $Day) { $ReturnVal .= "<option value='$i' selected>"; } else { $ReturnVal .= "<option value='$i'>"; } $ReturnVal .= "$i</option>"; } $ReturnVal .= "</select> <select name='$NamePre" . "Year'>"; for ($i=date('Y'); $i>=1900; $i=$i-1) { if ($i == $Year) { $ReturnVal .= "<option value='$i' selected>"; } else { $ReturnVal .= "<option value='$i'>$i</option>"; } $ReturnVal .= "$i</option>"; } $ReturnVal .= '</select> </td>
49
</tr>'; if (array_key_exists($NamePre . 'Date',$Errors)) { $ReturnVal .= addErrorRow($NamePre . 'Date',$Errors); } return $ReturnVal; } /* Function Name: addErrorRow Arguments: $Name Returns: table row as string */ function addErrorRow($Name,$Errors) { $ErrorRow = '<tr><td colspan="2" class="Error">* ' . $Errors[$Name] . '</td></tr>'; return $ErrorRow; } ?>
Code Explanation This file contains functions for presenting form entries. Several of these functions are complete, but there are a couple that need to be finished. This will be part of the next exercise.
/* Function Name: checkPassword Arguments: $PW1,$PW2 Returns: false if $PW1 has fewer than 6 characters false if $PW1 has more than 12 characters false if $PW1 and $PW2 do not match true otherwise
50
Code Explanation This file contains functions for validating form entries. One of these functions is complete, but there are a couple that need to be finished. This will also be part of the next exercise.
Code Explanation This file creates the entry form. Notice that it creates entry rows through calls to functions in the fnFormPresentation.php file. This allows us to easily incorporate error handling and error messages into the form entries without making the HTML form itself difficult to maintain.
51
$DbEntries['Password'] = dbString($_POST['Password1']); $DbEntries['Email'] = dbString($_POST['Email']); $DbEntries['BirthMonth'] = dbString($_POST['BirthMonth']); $DbEntries['BirthDay'] = dbString($_POST['BirthDay']); $DbEntries['BirthYear'] = dbString($_POST['BirthYear']); $DbEntries['HireMonth'] = dbString($_POST['HireMonth']); $DbEntries['HireDay'] = dbString($_POST['HireDay']); $DbEntries['HireYear'] = dbString($_POST['HireYear']); if (!checkLength($_POST['FirstName'])) { $Errors['FirstName'] = 'First name omitted.'; } else { $BrowserEntries['FirstName'] = browserString($_POST['FirstName']); } if (!checkLength($_POST['LastName'])) { $Errors['LastName'] = 'Last name omitted.'; } else { $BrowserEntries['LastName'] = browserString($_POST['LastName']); } if (!checkLength($_POST['Title'])) { $Errors['Title'] = 'Title omitted.'; } else { $BrowserEntries['Title'] = ucwords(browserString($_POST['Title'])); } if ( array_key_exists('TitleOfCourtesy',$_POST) ) { $BrowserEntries['TitleOfCourtesy'] = browserString($_POST['TitleOfCourtesy']); $DbEntries['TitleOfCourtesy'] = dbString($_POST['TitleOfCourtesy']); } else { $Errors['TitleOfCourtesy'] = 'Title of Courtesy not selected.'; } if (!checkdate($_POST['BirthMonth'],$_POST['BirthDay'],$_POST['BirthYear'])) { $Errors['BirthDate'] = 'Birth date is not a valid date.'; } if (!checkdate($_POST['HireMonth'],$_POST['HireDay'],$_POST['HireYear'])) { $Errors['HireDate'] = 'Hire date is not a valid date.'; } if (!checkLength($_POST['Address'],5,200)) { $Errors['Address'] = 'Address omitted.'; } else { $BrowserEntries['Address'] = browserString($_POST['Address']); } if (!checkLength($_POST['City'],1,100)) { $Errors['City'] = 'City omitted.'; } else { $BrowserEntries['City'] = browserString($_POST['City']); } if (!checkLength($_POST['Region'],2,2) && !checkLength($_POST['Region'],0,0)) { $Errors['Region'] = 'Region name must be two characters.'; } else { $BrowserEntries['Region'] = browserString($_POST['Region']);
52
} if (!checkLength($_POST['PostalCode'])) { $Errors['PostalCode'] = 'Postal Code omitted.'; } else { $BrowserEntries['PostalCode'] = browserString($_POST['PostalCode']); } if (!checkLength($_POST['Country'])) { $Errors['Country'] = 'Country omitted.'; } else { $BrowserEntries['Country'] = browserString($_POST['Country']); } if (!checkLength($_POST['HomePhone'],10,15)) { $Errors['HomePhone'] = 'Home phone must be between 10 and 15 characters.'; } else { $BrowserEntries['HomePhone'] = browserString($_POST['HomePhone']); } if (!checkLength($_POST['Extension'],3,5)) { $Errors['Extension'] = 'Extension must be between 3 and 5 characters.'; } else { $BrowserEntries['Extension'] = browserString($_POST['Extension']); } if (!checkLength($_POST['Notes'],0,100)) { $Errors['Notes'] = 'Notes must be fewer than 100 characters:<br/> <span style="color:blue; font-weight:normal">' . browserString(substr($_POST['Notes'],0,100)) . '</span><span style="color:red; font-weight:normal; text-decoration:line-through;">' . browserString(substr($_POST['Notes'],100)) . '</span>'; } else { $BrowserEntries['Notes'] = browserString($_POST['Notes']); } if ($_POST['ReportsTo'] == 0) { $Errors['ReportsTo'] = 'Manager not selected.'; } else { $BrowserEntries['ReportsTo'] = $_POST['ReportsTo']; } if ( !checkPassword($_POST['Password1'],$_POST['Password2']) ) { $Errors['Password'] = 'Passwords do not match or are not the right length.'; } else { $BrowserEntries['Password'] = browserString($_POST['Password1']); } if ( !checkEmail($_POST['Email']) ) { $Errors['Email'] = 'Email is invalid.'; } else { $BrowserEntries['Email'] = browserString($_POST['Email']); } ?> <?php
53
if (!count($Errors)) { $ShowForm = false; ?> <form method="post" action="AddEmployee.php"> <input type="hidden" name="Confirmed" value="true"> <?php echo '<h2>Confirm Entries</h2>'; echo '<ol>'; foreach ($BrowserEntries as $key=>$Entry) { if ($key=='ReportsTo') { echo "<li><b>Manager:</b> $MgrEntries[$Entry]</li>"; } else { echo "<li><b>$key:</b> $Entry</li>"; } } echo '</ol>'; foreach ($DbEntries as $key=>$Entry) { ?> <input type="hidden" name="<?php echo $key ?>" value="<?php echo $Entry ?>"> <?php } ?> <input type="submit" value="Confirm"> </form> <?php } else { $DbEntries = $_POST; } ?>
Code Explanation This file contains code for processing the form entries. It makes use of functions in the fnFormValidation.php file for validating entries. If no errors are found, it sets the boolean $ShowForm to false, so that the original form will not be displayed and it outputs all the entries (made browser-safe) to the browser for confirmation. If errors are found, it adds them to the $Errors array, which is passed into the form presentation functions, so that they can return code for displaying the errors. If there are errors, the boolean $ShowForm is left as true, so that the original form is redisplayed.
Code Explanation This file will eventually contain code for inserting the employee information into the database.
Querying a Database
The steps for querying a database in a PHP script are as follows: 1. 2. 3. 4. 5. Connect to the database. Send query to the database. Retrieve and store results sent back from the database. Output the results of the query to the browser. Free up resources and disconnect from the database.
mysqli() Overview
54
New in PHP5 is the mysqli library, which works with MySQL versions 4.1.3 and above and takes advantage of a new faster connection protocol in MySQL. The mysqli library provides two interfaces: an object-oriented interface and a procedural interface. The following two scripts use the two different interfaces to accomplish the same result.
55
<tr> <th>First Name</th> <th>Last Name</th> <th>Title</th> <th>Email</th> <th>Extension</th> </tr> <?php while ($Row = mysqli_fetch_assoc($Result)) { echo '<tr>'; echo '<td>' . $Row['FirstName'] . '</td>'; echo '<td>' . $Row['LastName'] . '</td>'; echo '<td>' . $Row['Title'] . '</td>'; echo '<td>' . $Row['Email'] . '</td>'; echo '<td align="right">x' . $Row['Extension'] . '</td>'; echo '</tr>'; } ?> </table> <?php mysqli_free_result($Result); mysqli_close($DB); } ?> </body> </html>
Procedural:
@$DB = mysqli_connect('localhost','root','pwdpwd','Northwind');
2.
3.
4.
To see if the connection was successful we check mysqli_connect_errno(), which returns an error number if there is a connection error or 0 if there is no error. If an error occurs, we output a message with mysqli_connect_error(). We use the procedural interface in both cases, because a connection object doesn't get created if the connection fails. To send the query to the database and store the results in a variable, we use: o Object-oriented: $Result = $DB->query($Query); o Procedural: $Result = mysqli_query($DB,$Query); To output the results of the query, we use: o Object-oriented:
o o o o o o o o o o o o o o o o o o
while ($Row = $Result->fetch_assoc()) { echo "<tr>"; echo "<td>" . $Row['FirstName'] . "</td>"; echo "<td>" . $Row['LastName'] . "</td>"; echo "<td>" . $Row['Title'] . "</td>"; echo "<td>" . $Row['Email'] . "</td>"; echo "<td align='right'>x" . $Row['Extension'] . "</td>"; echo "</tr>"; }
Procedural:
while ($Row = mysqli_fetch_assoc($Result)) { echo "<tr>"; echo "<td>" . $Row['FirstName'] . "</td>"; echo "<td>" . $Row['LastName'] . "</td>"; echo "<td>" . $Row['Title'] . "</td>"; echo "<td>" . $Row['Email'] . "</td>"; echo "<td align='right'>x" . $Row['Extension'] . "</td>";
56
o
}
echo "</tr>";
5.
o o o
$Result->free(); $DB->close();
Procedural:
mysqli_free_result($Result); mysqli_close($DB);
As you can see, the two scripts are pretty similar. We will use the object-oriented interface in future examples.
57
<input type="hidden" name="EmployeeID" value="' . $Row['EmployeeID'] . '"/> <input type="submit" name="Editing" value="Edit"/> </form></td>'; echo '</tr>'; } ?> </table> ---- Code Omitted ----
Code Explanation This file is similar to the SimpleQuery examples we saw earlier in this lesson. The only difference is that each row now has an edit form in the last column, which sends the employee's EmployeeID to EditEmployee.php.
Code Explanation This file is similar to the AddEmployee.php file we worked on earlier in the course. This one goes a step further though by connecting to the database to retrieve data to populate the form. It works as follows: 1. 2. At the very top, we include several files we will need for the application and we connect to the database. In the body, we include: o our header and footer files. o code that checks whether the user has already made updates and, if so, includes the processing file. o the file with code to retrieve the specified employee's data. o the file with code to display the filled-in form.
58
$Query = "SELECT FirstName, LastName, Title, TitleOfCourtesy, Email, MONTH(BirthDate) AS BirthMonth, DAYOFMONTH(BirthDate) AS BirthDay, YEAR(BirthDate) AS BirthYear, MONTH(HireDate) AS HireMonth, DAYOFMONTH(HireDate) AS HireDay, YEAR(HireDate) AS HireYear, Address, City, Region, PostalCode, Country, HomePhone, Extension, Notes, ReportsTo, Password FROM Employees WHERE EmployeeID = $EmployeeID"; $Result = $DB->query($Query); $DbEntries = $Result->fetch_assoc(); $Result->free(); ?>
Code Explanation This file contains the query that selects the specified employee's data and populates the $DbEntries array with the results.
Code Explanation This file is the same as the fnStrings.php file we saw before except that the dbString() function has been updated. It now checks to see if magic quotes are turned on. If they are, then form entries will be made database-safe "automagically", so it just returns the trimmed string. If they are not, then it uses addslashes() to make the string safe for database queries.
59
Code Explanation This file is the same as the fnFormValidation.php file we saw before except that the checkPassword() function now takes an additional parameter: $CheckLen, which when set to false, will prevent the function from returning false if a blank password is entered.
60
{ $ShowForm = false; ?> ---- Code Omitted ---} else { $DbEntries = $_POST; } ?>
Code Explanation This file is the same as the ProcessEmployee.php file we saw before with a few important changes: 1. Instead of assigning values from $_POST to $DbEntries one by one, we simply copy $_POST into $DbEntries and then loop through the array to pass each element through dbString(). Notice the use of the & to make $Entry a reference to rather than a copy of the array element. The call to checkPassword() now contains a third parameter to specify whether the function should return false if the password fields are not filled out. We only want to check the password length for new entries, not for updates. If the EmployeeID key exists in the $_POST array, then the Edit Employee form has been submitted and a database query will be executed to update the employee record.
2.
3.
Instead of hiding the form after an employee is inserted. Provide a new empty form, so that the user can enter another employee. Where is the solution?
61
Code Explanation Using the object-oriented interface, the process is as follows: 1. 2. 3. A query is created with question marks used as placeholders for parameters (input variables). A statement is prepared using the prepare() method, which takes a query as an argument. Parameters can be bound to the statement with the bind_param() method. The first argument of this method is a string that has one character for each subsequent argument. The character specifies the data type of that input parameter. For example, "isd" would specify that the input parameters are an integer, string, and double, in that order. The only other option is b for blob. The statement is executed with the execute() method. If the query returns results (e.g, SELECT queries), they can be bound to the statement with the bind_result() method. The fetch() method can be used to fetch rows from the result set.
4. 5. 6.
Prepared statements are most useful in cases where you have to loop through a dataset to do bulk inserts or updates.
62
Prepare Functions Object-oriented $db->prepare() $Stmt->bind_result() $Stmt->bind_param() $Stmt->execute() $Stmt->fetch() $Stmt->close() Procedural mysqli_prepare() mysqli_stmt_bind_result() mysqli_stmt_bind_param() mysqli_stmt_execute() mysqli_stmt_fetch() mysqli_stmt_close() Description Prepares a SQL statement for execution. Binds variables to a prepared statement results. Binds variables to a prepared statement. Executes a prepared statement. Fetches results into the bound variables. Closes prepared statement.
Footnotes
1. 2. The @ operator is used to suppress warnings in case the connection fails. To see the results, open the file in your browser passing a city (e.g, London) via the query string.
PEAR (see footnote) supplies a number of open source extensions to PHP including its DB package, which provides a database abstraction layer, so that the PHP programmer doesn't have to worry about all the APIs for different databases.
63
The biggest downside of using a database abstraction layer is that the benefits come at a performance cost. Imagine you were planning to travel around Europe and had the choice of bringing an interpreter who could speak all European languages and learning the languages yourself. It would certainly be easier to bring the interpreter, but this would make each conversation you had somewhat slower. The abstraction layer is the interpreter.
Using PEAR DB
The connection string for connecting to the database with PEAR DB is: Syntax
driver://username:password@host/database
64
<th>Last Name</th> <th>Title</th> <th>Email</th> <th>Extension</th> </tr> <?php while ($Row = $Result->fetchRow(DB_FETCHMODE_ASSOC)) { echo '<tr>'; echo '<td>' . $Row['FirstName'] . '</td>'; echo '<td>' . $Row['LastName'] . '</td>'; echo '<td>' . $Row['Title'] . '</td>'; echo '<td>' . $Row['Email'] . '</td>'; echo '<td align="right">x' . $Row['Extension'] . '</td>'; echo '</tr>'; } ?> </table> <?php $Result->free(); $DB->disconnect(); } ?> </body> </html>
Code Explanation As you can see, the PEAR DB API is very similar to the mysqli object-oriented API. Let's walk through the code. 1. First, we include the PEAR DB library. Notice that we simply use DB.php for the path:
require_once 'DB.php';
This will only work if: DB.php is in the same directory as EmployeeReport.php. This isn't likely as DB.php itself includes files, which would also have to be in the same directory. o The include_path directive in php.ini includes a path to the pear folder containing DB.php. 2. Next, we connect to the database:
@$DB = DB::connect('mysqli://root:pwdpwd@localhost/Northwind'); o
This line of code will create a connection object if the connection is successful or an error object if it is not. The :: syntax will be covered when we discuss object-oriented PHP programming, but the crux of it is that the connect() method is a class-level method rather than an object-level method, so it can be called without first instantiating an object. (see footnote)
65
3. We then use the class-level isError() method to check if $DB is an error object, which would mean that the connection failed. If it did fail, we output an error.
4. if (DB::isError($DB)) 5. { 6. echo 'Cannot connect to database: ' . $DB->getMessage(); }
10. And, after writing out our header row, we loop through the query results outputting a row for each record returned:
11. while ($Row = $Result->fetchRow(DB_FETCHMODE_ASSOC)) 12. { 13. echo '<tr>'; 14. echo '<td>' . $Row['FirstName'] . '</td>'; 15. echo '<td>' . $Row['LastName'] . '</td>'; 16. echo '<td>' . $Row['Title'] . '</td>'; 17. echo '<td>' . $Row['Email'] . '</td>'; 18. echo '<td align="right">x' . $Row['Extension'] . '</td>'; }
The fetchRow() method can take one of several constants to specify how a row is returned. In this example, we use DB_FETCHMODE_ASSOC to get the row as an associative array. Other options are DB_FETCHMODE_ORDERED (the default) and DB_FETCHMODE_OBJECT, which get the row as an indexed array and an object, respectively.
<html> <head> <title>Sales Report</title> </head> <body> <?php //Include PEAR DB Package //Connect to the Northwind database. // If the connection fails, return an error message to the browser. // If the connectoin succeeds run a query that gets the order date // and the first and last name of the associated employee // and the customer company for all orders. Order by OrderDate. ?> <table border="1"> <tr> <th>#</th> <th>Salesperson</th> <th>Customer</th> <th>Order Date</th> </tr> <?php //Create rows for each record returned from the query. ?> </table> <?php //Free the result and disconnect from the database. } ?> </body> </html>
830 rows are returned. This is two many to display on a single page. MySQL has a LIMIT clause that specifies which and how many records to return from the query. For example, the query below would return 10 orders starting with the 100th order (note that the first row is row 0).
SELECT OrderDate, OrderID FROM Orders LIMIT 99,10;
Add code to your solution that allows the user to tab through the results 10 at a time with Previous and Next buttons. Where is the solution?
PEAR:DB Conclusion
In thius lesson, you have learned to use PEAR-DB to connect to databases.
Footnotes
67
1. The homepage for PEAR is at http://pear.php.net/. For information on installing PEAR, visit http://pear.php.net/manual/en/installation.php. 2. If this doesn't make sense, don't worry about it. It will be clearer after you've learned about object-oriented programming.
68
<td>Password:</td> <td> <input type="password" name="Password" size="10"> </td> </tr> <tr> <td align="right" colspan="2"> <input type="submit" value="Log in"> </td> </tr> </table> </form> </div> <?php } require 'Includes/Footer.php'; ?> </body> </html>
Code Explanation This page contains an HTML login form, which submits to itself (i.e, the action points to the same page). A hidden field, LoggingIn, is passed to the server when the user submits the form. The script checks to see if LoggingIn exists in the $_POST array. If it does, it processes the form input:
$Email = $_POST['Email']; $PW = $_POST['Password']; if ($Email == 'jwayne@northwind.com' && $PW == 'cowboy') { echo '<div align="center">Success</div>'; } else { echo '<div align="center">Login Failed</div>'; unset($_POST['LoggingIn']); }
This code simply checks to see if the user's email and password match the hard-coded values (jwayne@northwind.com and cowboy). If they do, it outputs a "success" message. If they don't, it outputs a "failed" message and removes LoggingIn from the $_POST array, so that the form will be displayed again.
it includes several of the scripts we saw in earlier exercises. Most of these are exactly the same, but a small change has been made to the pwEntry() function in Authentication/Exercises/Includes/fnFormPresentation.php. It now takes a fifth parameter: $Repeat. When $Repeat is set to true (default), the user will be asked to repeat her password (used for registration forms). When $Repeat is set to false, she'll just get a single password field (used for login forms). 2. Your job is to finish Authentication/Exercises/Includes/LoginForm.php and Authentication/Exercises/Includes/Login.php, which are currently both nearly empty. You may find it helpful to refer to ManagingData/Demos/Includes/EmployeeForm.php when creating LoginForm.php and to ManagingData/Demos/Includes/ProcessEmployee.php when creating Login.php.
In this lesson of the PHP tutorial, you have learned how to authenticate users. Unfortunately, as it is currently written, only the index page itself is protected. To protect the whole site in this manner, we would have to force the user to log in to every page. That might frustrate our visitors a bit, so we'll learn how to allow users to log in to the whole site later in the course.
preg_replace()
The syntax for preg_replace() is as follows.
preg_replace(pattern, replacement, text_to_search);
71
<script> function usePattern(PATTERN) { document.formRE.Pattern.value=PATTERN; document.getElementById("display").innerHTML="<b>PATTERN: </b>" + PATTERN; } </script> </head> <body> <h2>Regular Expression Tester</h2> <form name="formRE" method="post"> <table> <tr> <td align="right"><span class="big">Text to search:</span></td> <td><input type="text" name="TextToSearch" value="<?= $TextToSearch ?>" size="50" maxlength="50"></td> </tr> <tr> <td align="right"><span class="big">Pattern:</span></td> <td><input type="text" name="Pattern" size="50" value="<?= $Pattern ?>" maxlength="100"></td> </tr> <tr> <td colspan="2" align="center">Try these patterns: <a href="javascript:usePattern('/^[a-zA-Z0-9_\\-\\.]+@[a-zA-Z0-9\\-]+\\.[azA-Z0-9\\-\\.]+$/');">Email</a> | <a href="javascript:usePattern('/^[0-9]{3}[\\- ]?[0-9]{2}[\\- ]?[09]{4}$/');">SSN</a> | <a href="javascript:usePattern('/^\\(?[2-9][0-9]{2}\\)?[\\- ]?[0-9]{3}[\\]?[0-9]{4}$/');">Phone</a> </td> </tr> <tr> <td colspan="2" align="center" style="font-size:18pt; font-family:Arial, Helvetica, sans-serif; background: #cccccc;"> <?php if (empty($Pattern)) echo '<span style="color:blue">Let\'s play!</span>'; elseif (preg_match($Pattern,$TextToSearch)) echo '<span style="color:green">Match</span>'; else echo '<span style="color:red">No Match</span>'; ?> </td> </tr> <tr align="center"> <td colspan="2"> <input type="submit" value="Submit"> <input type="reset"> </td> </tr> </table> </form>
72
<div id="display" style="font-size:18pt; font-family:Courier New"><b>PATTERN:</b> <?= $Pattern ?></div> </body> </html>
A dollar sign ($) at the end of a regular expression indicates that the string being searched must end with this pattern.
Number of Occurrences ( ? + * {} )
The following symbols affect the number of occurrences of the preceding character (see footnote): ?, +, *, and {}. A questionmark (?) indicates that the preceding character should appear zero or one times in the pattern.
The pattern foo? can be found in "food" and "fod", but not "faod".
A plus sign (+) indicates that the preceding character should appear one or more times in the pattern.
The pattern fo+ can be found in "fod", "food" and "foood", but not "fd".
A asterisk (*) indicates that the preceding character should appear zero or more times in the pattern.
73
Curly brackets with one parameter ( {n} ) indicate that the preceding character should appear exactly n times in the pattern.
The pattern fo{3}d can be found in "foood" , but not "food" or "fooood".
Curly brackets with two parameters ( {n1,n2} ) indicate that the preceding character should appear between n1 and n2 times in the pattern.
The pattern fo{2,4}d can be found in "food","foood" and "fooood", but not "fod" or "foooood".
Curly brackets with one parameter and an empty second paramenter ( {n,} ) indicate that the preceding character should appear at least n times in the pattern.
The pattern fo{2,}d can be found in "food" and "foooood", but not "fod".
Common Characters ( . \d \D \w \W \s \S )
A period ( . ) represents any character except a newline.
The pattern fo.d can be found in "food", "foad", "fo9d", and "fo*d".
The pattern fo\dd can be found in "fo1d", "fo4d" and "fo0d", but not in "food" or "fodd".
The pattern fo\Dd can be found in "food" and "foad", but not in "fo4d".
Backslash-w ( \w ) represents any word character (letters, digits, and the underscore (_) ).
The pattern fo\wd can be found in "food", "fo_d" and "fo4d", but not in "fo*d".
The pattern fo\Wd can be found in "fo*d", "fo@d" and "fo.d", but not in "food".
Backslash-s ( \s) represents any whitespace character (e.g, space, tab, newline, etc.).
The pattern fo\sd can be found in "fo d", but not in "food".
The pattern fo\Sd can be found in "fo*d", "food" and "fo4d", but not in "fo d".
74
Grouping ( [] )
Square brackets ( [] ) are used to group options. This creates what is referred to as a "character class".
The pattern f[aeiou]d can be found in "fad" and "fed", but not in "food", "faed" or "fd". The pattern f[aeiou]{2}d can be found in "faed" and "feod", but not in "fod", "fed" or "fd".
Negation ( ^ )
When used after the opening square bracket of a character class, the caret ( ^ ) is used for negation.
The pattern f[^aeiou]d can be found in "fqd" and "f4d", but not in "fad" or "fed".
Subpatterns ( () )
Parentheses ( () ) are used to capture subpatterns.
The pattern f(oo)?d can be found in "food" and "fd", but not in "fod".
Alternatives ( | )
The pipe ( | ) is used to create optional patterns.
The pattern foo$|^bar can be found in "foo" and "bar", but not "foobar".
Escape Character ( \ )
The backslash ( \ ) is used to escape special characters.
The pattern fo\.d can be found in "fo.d", but not in "food" or "fo4d".
75
$Email = trim($Email); if (!checkLength($Email,6)) { return false; } elseif (!strpos($Email,'@')) { return false; } elseif (!strpos($Email,'.')) { return false; } elseif (strrpos($Email,'.') < strpos($Email,'@')) { return false; } return true; }
We can use a regular expression to make this function both simpler and more powerful:
function checkEmail($Email) { $EmailPattern = '/^(\w+\.)*\w+@(\w+\.)+[A-Za-z]+$/'; return preg_match($EmailPattern,$Email)); }
A nice thing about this is that we can use virtually the same function to do client-side validation with JavaScript:
function checkEmail(EMAIL) { var reEmail = /^(\w+[\-\.])*\w+@(\w+\.)+[A-Za-z]+$/; return reEmail.test(EMAIL)); }
So, by using regular expressions in this way, you make it easy to create a similar function library on the client side.
Footnotes
1. Or characters if parentheses are used to create subpatterns.
76
Sessions
A session begins when a visiting client somehow identifies itself to the web server. The web server assigns the client a unique session id, which the client uses to re-identify itself as it moves from page to page on the website. Most of the time, these unique ids are stored in session cookies that expire after the client hasn't interacted with the server for some amount of time. The amount of time varies depending on the web application. For example, an online investment site might have very short sessions, so that if a user leaves her computer without logging out, another user who sits down at the same computer several minutes later cannot continue with the first user's session.
Configuring Sessions
In PHP, session management is configured in the php.ini file. To have a user's session start as soon as the user visits the website, the session.auto_start flag must be set to 1. The session length is also set in the php.ini file with the session.gc_maxlifetime variable. The default value is 1440 seconds (24 minutes).
Session Functions
The following table shows the most common session functions. Function Explanation session_start() Starts new session if one does not exist. Continues current session if one exists. session_unset() Unsets all session variables. session_destroy() Kills session. Together, the files below illustrate how sessions can be tracked.
77
Pages that are part of the session should begin with a call to session_start(). Session variables are created in the $_SESSION array. Session variables are deleted in the same way as other variables using the unset() function. All session variables can be unset with the session_unset() function. This should be called before calling session_destroy(). Sessions are killed with a call to session_destroy().
Cookies
Cookies are stored in text files that sit on the client machine. Web pages with the right permissions can read from and write to cookies. They are generally used to track user information between visits. In PHP, cookies are set with the setcookie() function, which can take several parameters including:
The cookie's expiration date (if this isn't set, the cookie will expire when the browser window is closed). The directory path on the server that can read the cookie. The domain name that can read the cookie. A flag indicating whether the cookie should only be read over https.
The following code will set a cookie that expires in one week.
setcookie('flavor','chocolate chip', time()+60*60*24*7);
There is no deletecookie() function. To delete a cookie, set the expiration date to sometime in the past, like this.
setcookie('flavor','chocolate chip', time()-10000);
Cookies are set in the HTTP header, so they must be set before any HTML code is passed back to the browser.
79
o o o o o o
2. Open Sessions/Exercises/Includes/Login.php (you can use LoginPear.php if you prefer) in your editor. Modify the code, so that when the user logs in, she is remembered for the duration of her visit. You should remember her first name, last name and employee id. 3. Sessions/Exercises/Includes/Footer.php has been changed to include a "Log out" link, which points to Sessions/Exercises/Logout.php. Open Sessions/Exercises/Logout.php in your editor. Add code to log the user out (i.e, delete all session variables and kill the session). 4. Open Sessions/Exercises/OtherPage.php in your editor. Notice that it includes Includes/LoginCheck.php. 5. Open Sessions/Exercises/Includes/LoginCheck.php in your editor. You will see that it currently contains code to redirect the page to index.php. Modify this script so that it only redirects to index.php if the user is not logged in. Write code so that the user can indicate that she would like to be remembered between visits. If she chooses to be remembered, she should not have to log in again for a week. You will need to modify index.php, Includes/LoginForm.php, Includes/Login.php and Includes/Logout.php. You may also find it useful to create a new include file (e.g, CookieCheck.php) to hold the code that checks for the cookie. Where is the solution?
mail()
PHP has a built-in mail() function that makes it easy to send email. Mail Parameters Description The address to send the email to. The email's subject. The body of the email.
80
Mail Parameters Description Optional. Additional headers (e.g, From, Reply-To) Optional. Any additional parameters you may want to send to your mail server.
Code Explanation For this example to work, you will need to have a mail server set up on your server.
81
The first time a visitor hits the page, he'll be presented with a form. When the user fills out and submits that form, the mail() function will attempt to send an email to the address the user entered. Note that the mail server is set with the ini_set() function, which is used to temporarily change configuration settings. You can set the default mail server in the php.ini file with the SMTP setting.
Shortcomings of mail()
The mail() function has many limitations.
No support for SMTP authentication. Difficult to send HTML-formatted emails. Difficult to add attachments.
PHPMailer
A very good email extension is PHPMailer, which is available for free at http://phpmailer.sourceforge.net. We will use PHPMailer in our examples and exercises. The following tables show some of the more common methods and properties of PHPMailer. PHPMailer Methods Method Description AddAddress() Adds a "To" address. AddAttachment() Adds an attachment from a path on the filesystem. AddBCC() Adds a "bcc" address. AddCC() Adds a "cc" address. AddReplyTo() Adds a "Reply-to" address. IsHTML() Sets message type to HTML. IsSMTP() Sets Mailer to send message using SMTP. Creates message and assigns Mailer. If the message is not sent successfully Send() then it returns false. PHPMailer Properties Property Description AltBody Sets the text-only body of the message. Body Sets the Body of the message. This can be either an HTML or text body. ErrorInfo Holds the most recent mailer error message. From Sets the From email address for the message.
82
PHPMailer Properties Property Description FromName Sets the From name of the message. Host Sets the SMTP hosts. All hosts must be separated by semicolons. Password Sets SMTP password. SMTPAuth Sets SMTP authentication. Utilizes the Username and Password properties. Subject Sets the Subject of the message. Username Sets SMTP username. WordWrap Sets word wrapping on the body of the message to a given number of characters.
83
$Mail->Username=$_POST['Username']; $Mail->Password=$_POST['Password']; } else { $HTML = false; } $Mail = new PHPMailer(); $Mail->IsSMTP(); // send via SMTP $Mail->Host = $Host; //SMTP server if (array_key_exists('Username',$_POST)) { $Mail->SMTPAuth=true; } else { $Mail->SMTPAuth=false; } $Mail->From = $From; $Mail->FromName = $FromName; $Mail->AddAddress($To); $Mail->AddReplyTo($From); $Mail->WordWrap = 50; // set word wrap $Mail->IsHTML($HTML); $Mail->Subject = $Subject; $Mail->Body = $Message; if($Mail->Send()) { echo "Message Sent"; } else { echo "Message Not Sent<br/>"; echo "Mailer Error: " . $Mail->ErrorInfo; } } ?> </body> </html>
Code Explanation As you can see, PHPMailer comes with a full set of intuitive methods and properties that make sending emails very easy.
In this exercise, you will create a Password Reminder page that allows users to have their passwords sent to them by email. 1. Open Mail/Exercises/PasswordReminder.php in your editor. 2. This page contains a simple form that submits to the same page. 3. In the else block of the if condition add code that sends the user her password, which you'll need to get from the Northwind database. 4. BCC yourself on the email. You'll need this to check to see that your solution is working. 5. If the email fails to send, output the error to the browser. Otherwise, let the user know the password has been sent. 6. Test your solution in your browser. Where is the solution?
Opening a File
fopen()
Syntax
fopen (path_to_file, file_mode)
path_to_file can either be a relative or an absolute path. File Modes File Mode r w a x r+ w+ Description open for reading open for writing (erases existing content); creates new file if one doesn't exist open for appending to end of content; creates new file if one doesn't exist create and open for writing (new in PHP 4.3.2); fails and returns false if file already exists open for reading and writing (erases existing content when file is written to) open for writing and reading (erases existing content on opening or creates new file if one doesn't exist
85
File Modes File Mode a+ x+ Description open for appending and writing; creates new file if one doesn't exist create and open for writing and reading (new in PHP 4.3.2); fails and returns false if file already exists
File Permissions
Files that do no have the appropriate permissions settings will fail to open. In this case, the fopen() function will return false and a warning will be given. Use conditional processing as shown below to handle this situation.
$MyFile = @fopen('MyFile.txt','a'); if (!$MyFile) { echo '<b>Sorry, but the file cannot be opened.</b>'; } else { // code for processing file }
The @ symbol in front of first line of code is used to suppress errors. Any errors can then be handled more gracefully.
fgets()
fgets() is used to read a file one line at a time. It requires one argument: the resource or "handle" for the file and accepts a second argument: the length of the line. It will continue reading the line until the length - 1 have been read or it reaches the end of the line or the end of the file. If the second argument is not included, it will continue reading until it reaches the end of the line. Examine the file shown below.
Nancy Davolio Sales Representative ndavolio@northwind.com Andrew Fuller Vice President, Sales afuller@northwind.com Janet Leverling Sales Representative jleverling@northwind.com Margaret Peacock Sales Representative mpeacock@northwind.com Steven Buchanan Sales Manager sbuchanan@northwind.com Michael Suyama Sales Representative msuyama@northwind.com Robert King Sales Representative rking@northwind.com Laura Callahan Inside Sales Coordinator lcallahan@northwind.com Anne Dodsworth Sales Representative adodsworth@northwind.com
Code Explanation Employees.txt is a tab-delimited text file. Each line is formatted as follows:
FirstName\tLastName\tTitle\tEmail\n
The file is divided into "columns" using tabs (\t) and each "row" is separated by a newline character (\n). The code below opens Employees.txt, reads and displays each line, and closes the file.
Other options for reading from files Function Description fgetss() Like fgets() but it strips out HTML and PHP tags. fgetcsv() Like fgets() but it splits the file on a specified delimiter rather than a newline
87
Function
character. readfile() Opens a file, sends its contents to the browser, and closes the file. file() Opens a file, splits it into an array on newline characters, and closes the file.
Writing to a File
Opening a file for writing involves three steps: 1. Open the file. 2. Write to the file. 3. Close the file.
fwrite()
Syntax
fwrite(file_pointer,output_string)
The output_string is the text to write to the file. See the following example of writing to a file.
$OutputString='text to write'; $MyFile = @fopen('Employees.txt', 'a'); fwrite($MyFile, $OutputString); fclose($MyFile);
File Locking
88
The following example demonstrates how to safely allow the user to upload a file to the server.
89
<body style="text-align:center"> <?php if (!array_key_exists('Submitted',$_POST)) { ?> <h2>Resume Upload Form</h2> <form method="post" enctype="multipart/form-data"> <input type="hidden" name="Submitted" value="true"> <table border="1"> <tr> <td>First Name</td> <td><input type="text" name="FirstName" size="20"></td> </tr> <tr> <td>Last Name</td> <td><input type="text" name="LastName" size="20"></td> </tr> <tr> <td>Resume</td> <td><input type="file" name="Resume"></td> </tr> <tr> <td colspan="2" align="center"><input type="submit" value="Upload"></td> </tr> </table> </form> <?php } else { //process the form $ResumeFile = $_FILES['Resume']['tmp_name']; $FileSize = $_FILES['Resume']['size']; $FileType = $_FILES['Resume']['type']; $FileError = $_FILES['Resume']['error']; $ResumeName=$_POST['FirstName'] . '_' . $_POST['LastName'] . '_Resume.txt'; if ($FileError) { echo "We could not upload the file:<br/>$FileError"; EndPage(); } elseif ($FileType != 'text/plain') { echo "You have attempted to upload a file of type: $FileType. <br/>Only text files allowed."; EndPage(); } $FileSavePath = 'Resumes/' . $ResumeName; if (is_uploaded_file($ResumeFile)) { if (!move_uploaded_file($ResumeFile,$FileSavePath)) { echo 'Could not save file.'; EndPage(); } } else
90
{ //This case happens if somehow the file //we are working with was already on the server. //It's to stop hackers. echo 'Hey, what is going on here? Are you being bad?'; EndPage(); } $Resume=makeFileSafe($FileSavePath); ?> <h2>Thanks!</h2> <b>We got your resume.</b><hr> <form> <textarea cols="60" rows="20"><?echo $Resume?></textarea> </form> </p> <?php } function EndPage() { echo '</body></html>'; exit; } function makeFileSafe($FilePath) { $FP = @fopen($FilePath,'r+'); if (!$FP) { return "Could not read file"; } $Contents = fread($FP,filesize($FilePath)); $Contents = strip_tags($Contents); rewind($FP); fwrite($FP,$Contents); fclose($FP); return $Contents; } ?> </body> </html>
Code Explanation The first thing to notice about this page is that it submits to itself. The first time it is loaded, it will show the form. When the form is submitted, it will attempt to upload and save the user's resume. 1. The form also has an input field of type file that is used to browse for the file to upload. 2. When the form is submitted, the script assigns values to short named variables. 3. The next block of code is the if-elseif-elseif statement, which checks for errors. If it finds any, it displays an appropriate message and calls the EndPage() user function, which just closes the HTML page.
91
21. The last bit of PHP code on the page calls the makeFileSafe() user function which opens the resume file, strips out all the tags from its contents and closes it.
92
echo 'is_readable: ' . (is_readable($File)? 'true' : 'false').'<br/>'; echo 'is_writable: ' . (is_writable($File)? 'true' : 'false').'<br/>'; ?> </body> </html>
Code Explanation The functions used in this script are described in the following table. Function Description basename() Strips off the path and returns the file name. fileatime() Returns the last accessed time of the file. filemtime() Returns the last modified time of the file. filetype() Returns the type of file (e.g, file or dir). filesize() Returns the size of the file in bytes. is_dir() Returns true if the passed value is a directory, false if it isn't. is_file() Returns true if the passed value is a file, false if it isn't. is_readable() Returns true if the file is readable, false if it isn't. is_writable() Returns true if the file is writable, false if it isn't.
Directory Functions
The following table shows some of the more common directory functions. Function Description
93
Function Description mkdir() Creates a directory. rmdir() Deletes a directory. opendir() Opens a directory for reading. readdir() Reads the contents of an open directory.
94
Footnotes
1. flock() does not work with NFS or other networked file systems or with older systems such as FAT that do not support file locking. 2. For file uploads to work, the file_uploads flag in php.ini must be turned on
95