PHP Basics

In this lesson of the PHP tutorial, you will learn... 1. 2. 3. 4. 5. How PHP works. To write a simple PHP page. To understand and work with simple PHP variables. To use PHP operators. To pass values from one page to another via the URL.

How PHP Works
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.

The php.ini File
Before we look at PHP syntax, we should briefly mention the php.ini file. This is a plain text file that is used to configure PHP. When the PHP interpreter is started, it reads the php.ini file to determine what settings to use. We will mention this file from time to time throughout the course, but for now, it is enough that you are aware of its existence.

Basic PHP Syntax
PHP Tags
PHP code must be contained in special tags so that the PHP interpreter can identify it. Depending on the PHP configuration, these tags can take several forms:
<?php PHP CODE GOES IN HERE ?>

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.

<script language="php" > HTML or Script style tags. PHP CODE GOES IN HERE </script> <? PHP CODE "Short" tags. (see footnote) GOES HERE ?> <% PHP CODE ASP-style tags. (see footnote) GOES HERE %>

In this manual, we will use the first form shown as it is the most common and the most portable.

PHP Statements and Whitespace
PHP statements must be inside of PHP tags to be processed by the PHP interpreter. Each PHP statement must end with a semi-colon, which tells the PHP interpreter that the statement is complete. If a semi-colon does not appear at the end of a line, the interpreter will assume that the statement continues onto the next line.

The PHP interpreter condenses all sequential whitespace in PHP scripts to a single whitespace. This convenient feature allows PHP developers to structure their code in a readable format without being concerned about the effects of line breaks and tabs.

Comments
PHP has two forms of comments:
• •

Single-line comments begin with a double slash (//). Multi-line comments begin with "/*" and end with "*/".

Syntax
// This is a single-line comment /* This is a multi-line comment. */

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);

The example below shows how the phpinfo() function works.

Code Sample: PhpBasics/Demos/PhpInfo.php
<html> <head> <title>PHPINFO</title> </head> <body> <?php //Output information on the PHP environment phpinfo(); ?> </body> </html>

This code isn't very exciting.net PHP functions are well documented at http://www.net/function_name. There is nothing dynamic about this script. . ?> </body> </html> Code Explanation Notice the following about the above code: • • Code between <?php and ?> is processed by the PHP interpreter.php. we'll take a look at some more interesting examples. In fact.net. The echo command is used to print text back to the browser. (see footnote) Hello World! It is an unwritten rule that every programming course must contain a "Hello World!" script. to see documentation on phpinfo().php.Introduction to php. go to http://www.php <html> <head> <title>Hello World!</title> </head> <body> <?php //Write out Hello World! echo 'Hello World!'. Syntax $var_name = "Value". You can quickly look up documentation on a function by going to http://www. Variables PHP variables begin with a dollar sign ($) as shown below. For example. After learning about variables. PHP doesn't buy us anything here as we could have just as easily output the result using straight HTML.php.net/phpinfo. Here it is: Code Sample: PhpBasics/Demos/HelloWorld.

Rather. ?> </body> . underscores and dollar signs cannot begin with a digit are case sensitive Type Strength PHP is weakly typed. Code Sample: PhpBasics/Demos/HelloVariables. Hello Variables! Here is the "Hello World!" script again. ?> <html> <head> <title><?php echo $Greeting. ?></title> </head> <body> <?php echo $Greeting.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 Variable Names (Identifiers (see footnote)) • • • consist of letters. digits.g. meaning that variables do not need to be assigned a type (e. Integer) at the time they are declared.php <?php $Greeting = 'Hello World!'. the type of a PHP variable is determined by the value the variable holds and the way in which it is used. but this time we use a variable.

3. In this exercise.g.</html> Code Explanation This time the string "Hello World!" is stored in the $Greeting variable. 2. . Open a new document and save it as Today. 1. "Monday") to $Today.php in the PhpBasics/Exercises folder. Variable Scope A variable's scope determines the locations from which the variable can be accessed. visit http://www.net/date. which is output in the title and body of the page with an echo command. Test your solution in a browser.php. use the built-in date() function so that the script won't have to be manually updated every day to stay current. 4. For documentation. Output $Today in the title and body of the page. The resulting HTML page should look like this: Instead of assigning a literal string (e. The script will declare a variable called $Today that stores the day of the week. Exercise: First PHP Script Duration: 5 to 10 minutes. global. you will write a simple PHP script from scratch. or local. PHP variables are either superglobal. Declare a variable called $Today that holds the current day of the week as literal text.

including $_POST and $_GET and are accessible from anywhere on the page. They are accessible from anywhere on the page. The elements within superglobal variables can be accessed in three different ways. Short $varname • Mediu $_GET['varname'] m • • . Local variables are local to the function in which they are declared. • • • • • • • • $_GET . global Global variables are visible throughout the script in which they are declared.variables containing information about uploaded files.cookie variables. The complete list of superglobals is shown below. (see footnote) Style Syntax (using $_GET) • Notes Convenient. (see footnote) $_REQUEST .PHP environment variables (e. Recommended approach. However.session variables. $_POST . $_SERVER . $_COOKIE . and long style. $_ENV['HTTP_HOST'] returns the name of the host server. Requires register_globals config setting to be on.variables passed into a page through forms.server environment variables (e. Variables in the function scope are called local variables. $_SESSION . the query string and cookies.variables passed into a page through a form using the post method. function Superglobals Again. $_FILES . but it makes it difficult to distinguish superglobal variables from other variables in the code.Variable Scope Explanation superglob Superglobal variables are predefined arrays.g. which the authors of PHP and MySQL Web Development refer to as short style.variables passed into a page on the query string. medium style. superglobal variables are predefined arrays. Happy medium between convenience and clarity. they are not visible within functions in the script unless they are re-declared within the function as global variables. including $_POST and al $_GET.g. $_ENV . $_SERVER['HTTP_REFERER'] returns the URL of the referring page).

PHP Operators Operators in PHP are similar to those found in many modern C-like programming languages.VALUE). Deprecated. and removing a variable. they cannot be changed. Constants are created using the define() function and by convention (but not by rule) are in all uppercase letters. ) non-false value. once assigned a value.Style Syntax (using $_GET) • • • Notes Not available before v. Long $HTTP_GET_VARS['varn ame'] • Many of these superglobals will be covered later in the course. Constants Constants are like variables except that. but still supported in current versions. Syntax define('CONST_NAME'. Constants can be accessed from anywhere on the page. Exampl e isset($a) unset($ a) empty($ a) unset() Removes a variable from memory. checking if a variable holds a value. empty( Checks to see if a variable contains a non-empty. Returns true or false. (see footnote) Functi on isset() Explanation Checks to see if a variable exists. .ini file. Inconvenient to type. Variable-Testing and Manipulation Functions (see footnote) PHP provides built-in functions for checking if a variable exists. 4. Can be disabled via the register_long_arrays directive in the php.1.

++$a. $c = 'Hello' . ' on world!' Assignment Operators Operat or = += -= *= /= %= . $a = @(1/0). ' world!'.$b Multiplicati $a * $b on Division Modulus $a / $b $a % $b String Operators Operat or .Mathematical Operators Operat or + * / % Name Addition Exam ple $a + $b Subtraction $a . Combination Assignment Increment By One Decrement By One Other Operators Operat or ?: @ Name Ternary Error Example $foo = ($age >= 18) ? 'adult' : 'child'. $a += 1. $a /= 2. . $a . $a++. $a -= 1. $a--. $a %= 2.= ' world!'. $a *= 2. $b 'Hello' . Name Example Concatenati $a .= ++ -- Name Assignment Example $a = 1. --$a.

. the string "\tHello\n$person!!" will be output literally. echo '\tHello\n$person!!'. for simple strings you can use single quotes and double quotes interchangeably. ?> </body> </html> Because of the use of single quotes above. Compare the examples below. as shown below.php <html> <head> <title>Single Quotes</title> </head> <body> <?php $person = 'George'. Code Sample: PhpBasics/Demos/SingleQuotes. However.Other Operators Operat or Name Suppression Example Creating Dynamic Pages Single Quotes vs. there is one important difference of which you need to be aware. Text within single quotes will not be parsed for variables and escape sequences (see footnote). Double Quotes In PHP.

Code Sample: PhpBasics/Demos/DoubleQuotes. the string will be parsed for variables and special characters and will be output as shown below. . echo "\tHello\n$person!!".php <html> <head> <title>Single Quotes</title> </head> <body> <?php $person = "George". ?> </body> </html> This time. because of the double quotes.

The HTML page below shows an example of how these name-value pairs might be passed.webucator. The processing page can read these name-value pairs and use them to determine its response.html <html> <head> <title>Preferred Greeting</title> </head> <body> Do you prefer a formal greeting or an informal greeting? <ul> . Passing Variables on the URL A common way to pass values from the browser to the server is by appending them to the URL as follows: Syntax http://www. you will have to view the source of the resulting page. Code Sample: PhpBasics/Demos/HelloHi.com/hello.To see the effect of the special characters (\n and \t). One or more name-value pairs can be passed to the server in this way. Each name-value pair is separated by an ampersand (&).php?greet=Hello&who=World The part of the URL that follows the question mark is called the query string.

Change the links so that each Beatle gets a custom greeting (e. Hey Ringo). Howdy Paul. John. $greeting = $_GET['greet']. and Ringo) to HelloWho. Hi John.php <?php //Assign the passed variable to a variable with //a more convenient name.html in your editor.php. Bye George.php?greet=Hi">Informal</a></li> <li><a href="HelloHi. 3. 4. Open PhpBasics/Exercises/HelloWho. 1. 2. ?> </body> </html> Code Explanation Notice the following about the code above. Open PhpBasics/Exercises/HelloWho. each of which passes the name of one of the Beatles (Paul. George. In this exercise. is <?= 'text to print' ?>. you will write a script that says hello to different people based on what is passed through the query string. Try it out in your browser. You will see that it is the same as the demo we looked at earlier.html so that it has four links. • • • Variable names begin with a dollar sign ($).html.php?greet=Howdy">Friendly</a></li> </ul> </body> </html> Code Sample: PhpBasics/Demos/HelloHi. Modify HelloWho. Modify the code so that it outputs a greeting based on the link clicked on HelloWho. . which is in the same directory. A shortcut for echo 'text to print'.php?greet=Hello">Formal</a></li> <li><a href="HelloHi. ?> <html> <head> <title><?= $greeting ?> World!</title> </head> <body> <?php echo "$greeting World!". (see footnote) Exercise: Passing Variables via the Query String Duration: 10 to 15 minutes.<li><a href="HelloHi.php in your editor.g. Values passed in the query string are part of the $_GET array and can be accessed using the following syntax: $_GET['fieldname'].

Variable.Where is the solution? PHP Basics Conclusion In this lesson of the PHP tutorial. Common escape sequences are \n for a newline. Escape sequences are used for characters that cannot easily be output within strings. To work with if-elseif-else conditions in PHP. use the var_dump() function (e. . 3. 4. p. to recognize and look up documentation on PHP functions. To work with switch/case statements in PHP. Flow Control In this lesson of the PHP tutorial. 21-22 7. you have learned how to write a simple PHP page. function and class names are all identifiers and all follow the rules above.phpdig.ini configuration file directive. For a complete list of variable functions see http://www..g. with the exception that function names are not case sensitive. One reason for this is that the shortcut syntax makes the resulting PHP file impossible to parse as XML.net/manual/en/ref. 5. you will learn. 9. Another very good function reference is located at http://www. \\ for a backaslash. and \$ for a dollar sign. PHP & MySQL Web Development. 8. 6. Third Edition. 2. To output the results of these functions to a browser. Must be enabled via the asp_tags php.variables. 2. to work with variables and to pass variables from one page to another via the query string.php. 1..php.net/ref/. var_dump(isset($a)). Which environment variables are available depends on the specific server setup and configuration. Many PHP developers feel that it is best practice to avoid using this shortcut syntax for echo. 10.ini configuration file directive. \" for a double quote. Footnotes 1. Must be enabled via the short_open_tag php.). \t for a tab.

To work with loops in PHP. depending on the result of the if condition. the Do this. If Conditions Simple if statement Syntax if (conditions) Do this. Then do this. use the following syntax. Syntax if (conditions) { Do this.3. There are two conditional structures in PHP . statement will either run or not run depending on whether or not the conditions are true. And this too. if-else statement Syntax if (conditions) { Do this. which is surrounded by curly brackets to indicate that all of the code either should or should not be executed. } if-elseif-else statement Syntax if (conditions) { Do this. In the above code. Conditional Processing Conditional processing allows programmers to output different code based on specific conditions.if-elseif-else and switch/case. } The lines of code affected by the if condition are put in a code block. . } else { Do that. This syntax can only be used when the condition affects a single line of code. For a block of code.

} 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.} elseif (other conditions) { Do that. if ($Age >= 21) { echo 'You can vote and drink!'. The following table shows PHP's comparison operators.php <html> <head> <title>if-elseif-else</title> </head> <body> <?php $Age = 21. } . Code Sample: FlowControl/Demos/If. Comparison Operators Operat or == != > < >= <= === !== 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 Description The following example demonstrates an if-elseif-else statement.

The table below shows and and or operators for checking multiple conditions and the not operator for negating a boolean value (i. but can\'t drink.elseif ($Age >= 18) { echo 'You can vote. Compound If Statements More complex if statements often require that several conditions be checked. $Citizen = false. } else { echo 'You cannot vote or drink. Code Sample: FlowControl/Demos/If2. } .'.php <html> <head> <title>if-elseif-else</title> </head> <body> <?php $Age = 21. Logical Operators Operat Nam Exampl or e e && || ! AND $a && $b OR $a || $b NOT !$b The following example shows these logical operators in practice. You can see the different results by changing the value of $Age. but can\'t vote. } elseif ($Age >= 21) { echo 'You can vote and drink!'. if ($Age >= 21 && !$Citizen) { echo 'You can drink. turning true to false or vice versa).'.e. } ?> </body> </html> Code Explanation The file is relatively simple.'.

. default : echo 'expression is break. but can\'t drink. switch ($Quantity) { case 1 : echo 'Quantity is 1'. } a'. Code Sample: FlowControl/Demos/Switch. for example. be used to check if one value is higher than another.'. case 'c' : echo 'expression is break. case 'b' : echo 'expression is break. } else { echo 'You cannot vote or drink. except that it can only check for an equality comparison of a single expression. The break statement is important. } ?> </body> </html> switch/case A switch/case statement is similar to an if statement. Syntax switch (expression) { case 'a' : echo 'expression is break.'.php <html> <head> <title>switch/case</title> </head> <body> <?php $Quantity = 1. It cannot. Without it.elseif ($Age >= 18 && $Citizen) { echo 'You can vote. all following statements will execute. The following example demonstrates a switch/case statement without break statements. c'. unknown'. b'. after a single match is found.

default : echo 'Quantity is not 1 or 2'. } ?> </body> . break. } ?> </body> </html> Code Explanation The screenshot below shows the result.php <html> <head> <title>switch/case</title> </head> <body> <?php $Quantity = 1. case 2 : echo 'Quantity is 2'. Code Sample: FlowControl/Demos/SwitchWithBreak. default : echo 'Quantity is not 1 or 2'.case 2 : echo 'Quantity is 2'. Notice that. once a match is found. The following example shows how this can be fixed by adding break statements. break. all remaining echo statements are output. switch ($Quantity) { case 1 : echo 'Quantity is 1'.

</html> Code Explanation This time. This is the form that will be submitted. This form is submitted using the get method (see footnote). In this exercise. it looks like this: 1. 1. . which means the form entries will be appended to the query string and will be accessible in the $_GET array. Open FlowControl/Exercises/Greeting.html in your editor and review the code. you will create a page for handling a simple form submission. Filled out. only the first statement is output: Exercise: Working with Conditions Duration: 20 to 30 minutes.

o If the user filled out both fields. The following section shows the syntax for different types of loops...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. Try to find the function at http://www.. write out an error message to the screen.while for foreach (see footnote) while while loops are used to execute a block of code repeatedly while one or more conditions is true. loops are used to loop (or iterate) over code blocks. "MALE" and "FEMALE" may not be recognized as valid genders. return a gender-appropriate greeting such as "Hello Mr. Dunn!" If the gender is not recognizable (e.while loops is that the condition is checked after the code block is executed.while do. Loops As the name implies..php in your editor.. o If the user failed to fill out either one of the fields. Each loop will return "12345". It is likely that your solution does not take into account different cases for the gender. Dunn!" or "Hello Ms.2. } do.. while ($a < 6) { echo $a. 4. in a do.. Open FlowControl/Exercises/Greeting. test your solution in your browser. . 5. Try to use both an if condition and a switch statement in this exercise.while loop. $a++.. 3. • • • • while do. Insert a PHP block that checks to see if the user filled out both the LastName and the Gender fields in the form.g..while loops are used to execute a block of code repeatedly until one or more conditions is found to be false. not male or female).php. Syntax $a=1. The difference between while loops and do. the code block will always be executed at least once. For example. There are several types of loops in PHP. This means that. return an error message.. When you are done.

The third expression is executed at the end of each iteration through the loop. The second expression is evaluated before each iteration through the loop. do { echo $a. It is usually used to make changes that can affect the second expression. $a < 6. $a++. for A for loop takes three expressions separated by semi-colons and grouped in parentheses before the block to be iterated through. } } To jump to the next iteration of a loop without executing the remaining statements in the block. If it evaluates to false. Syntax for ($a=1. $a++) { echo $a. The first expression is executed once before the loop starts. 3. Syntax for ($a=1. insert a break statement. $a++) { . $a < 6.Syntax $a=1. the loop ends. 1. } break and continue To break out of a loop. 2. $a++) { echo $a. insert a continue statement. Syntax for ($a=1. if ($a > 3) { break. $a < 6. It is usually used to initialize the conditions. } while ($a < 6).

In both loops. we have dealt only with variables that store single values.php in your editor. skip all numbers that are divisible by 3. use a for loop to output all the odd numbers that are less than or equal to 100. Initializing Arrays Arrays are initialized with the array() function. we will be covering arrays. 1. associative arrays. Arrays In this lesson of the PHP tutorial. . array-manipulation functions. called scalar variables. Under the while header. Under the for header. An indexed array can contain zero or more elements. In this lesson. the first element of an array is in the "zeroeth" position. In PHP. Indexed Arrays Indexed arrays are similar to tables with a single column. Syntax $Beatles = array(). An array with no elements has a zero length. 3. Exercise: Working with Loops Duration: 10 to 15 minutes. 4. Arrays are variables that store sets of values. 2. Open FlowControl/Exercises/Loops. like in many programming languages. 1. 2. To To To To work work work work with with with with indexed arrays. 3. } echo $a. you will learn..} if ($a == 3) { continue. which can take a list of comma-delimited values that become the elements in the new array.. use a while loop to output all the even numbers that are less than or equal to 100. Be careful not to get caught in an infinite loop. Up to this point. The following lines of code initializes a zero-length array and then adds four elements to the array. two-dimensional arrays.

Reading from Arrays Reading from arrays is just a matter of pointing to a specific index or key. it is a better coding practice to explicitly initialize the array.'Paul'. For example. PHP provides an easy way of appending to an array of any length. The first line above is actually optional as the second line will create the array if one does not already exist. you can append to the array by specifying the index.'Ringo'). However. However. } . you could append to the $Beatles array shown above as follows: Syntax $Beatles[5] = 'Nat'. 'Ringo'. sometimes you don't know how many elements are in an array. Appending to an Array If you know how many elements are in an array. Syntax $Beatles[] = 'Nat'.'George'. The $Beatles array could also be created in a single line as follows. Syntax echo $Beatles[2].$Beatles[0] $Beatles[1] $Beatles[2] $Beatles[3] = = = = 'John'. Simply leave out the index. doing so requires an extra step. Syntax foreach ($Beatles as $Beatle) { echo "$Beatle<br>". 'Paul'. Although you can easily figure this out. 'George'. Syntax $Beatles = array('John'. //outputs George to the browser Looping through Arrays The following code will loop through the entire $Beatles array outputting each element to the browser.

echo $Beatles[2]. In this exercise. you will use arrays to create a table with a single column that lists all your favorite colors.The above code snippets are combined in the following example. $Beatles[2] = 'George'. ?> <hr/> <?php foreach ($Beatles as $Beatle) { echo "$Beatle<br/>". //outputs George to the browser $Beatles[] = 'Nat'. . } ?> </body> </html> Exercise: Working with Indexed Arrays Duration: 10 to 15 minutes. (see footnote) As shown in the screenshot below.php <html> <head> <title>Indexed Arrays</title> </head> <body> <h1>Indexed Arrays</h1> <?php $Beatles = array(). Code Sample: Arrays/Demos/IndexedArrays. $Beatles[1] = 'Paul'. $Beatles[0] = 'John'. the background of each table row should be the same as the color named in the row. $Beatles[3] = 'Ringo'.

= 'George'. instead of Ringo being indexed as 3.1. we can intialize a zero-length associative array and then add elements. For example. Create an array that holds your favorite colors.php for editing. Inside of the open and close <table> tags. Associative Arrays Whereas indexed arrays are indexed numerically. Test your solution in a browser. Syntax . 'John'. Or the array could be created in a single line as follows. loop through the array outputting a table row for each element. 2. he could be indexed as "drummer". 3. Open Arrays/Exercises/ColorTable. 4. Syntax $Beatles = array(). $Beatles['singer1'] = $Beatles['singer2'] = $Beatles['guitarist'] $Beatles['drummer'] = 'Paul'. Initializing Associative Arrays Like with indexed arrays. 'Ringo'. associative arrays are indexed using names.

'drummer' => 'Ringo'). Syntax foreach ($Beatles as $key => $Beatle) { echo "<b>$key:</b> $Beatle<br>". Reading from Associative Arrays Reading from associative arrays is as simple as reading from indexed arrays.$Beatles = array('singer1' => 'John'. Syntax echo $Beatles['drummer']. 'guitarist' => 'George'. 'singer2' => 'Paul'. } The above code snippets are combined in the following example. //outputs Ringo to the browser ?> <hr/> <?php foreach ($Beatles as $key => $Beatle) { echo "<b>$key:</b> $Beatle<br/>". } ?> </body> </html> . 'guitarist' => 'George'. echo $Beatles['drummer'].php <html> <head> <title>Associative Arrays</title> </head> <body> <h1>Associative Arrays</h1> <?php $Beatles = array('singer1' => 'John'. 'drummer' => 'Ringo'). 'singer2' => 'Paul'. //outputs Ringo to the browser Looping through Associative Arrays The following code will loop through the entire $Beatles array outputting each element and its key to the browser. Code Sample: Arrays/Demos/AssociativeArrays.

php <?php session_start(). The file below outputs all the contents of the superglobal arrays using foreach loops. ?> <html> <head> <title>Superglobal Arrays</title> </head> <body> <h1>Superglobal Arrays</h1> <h2>$_COOKIE</h2> <ol> <?php foreach ($_COOKIE as $key => $item) { echo "<li><b>$key:</b> $item<br/></li>". } ?> </ol> <hr/> <h2>$_FILES</h2> <ol> <?php foreach ($_FILES as $key => $item) { echo "<li><b>$key:</b> $item<br/></li>". Code Sample: Arrays/Demos/SuperGlobals.Superglobal Arrays The superglobal arrays are associative arrays. } ?> </ol> <hr/> <h2>$_GET</h2> <ol> <?php foreach ($_GET as $key => $item) { echo "<li><b>$key:</b> $item<br/></li>". } ?> </ol> <hr/> <h2>$_ENV</h2> <ol> <?php foreach ($_ENV as $key => $item) { echo "<li><b>$key:</b> $item<br/></li>". } ?> </ol> .

} ?> </ol> <hr/> <h2>$_SERVER</h2> <ol> <?php foreach ($_SERVER as $key => $item) { echo "<li><b>$key:</b> $item<br/></li>". Exercise: Working with Associative Arrays Duration: 10 to 15 minutes. The background of each table row should be the same as the color named in the row as shown in the screenshot below. you will use arrays to create a table with two columns that lists all your favorite colors and their hexadecimal equivalents. } ?> </ol> <hr/> <h2>$_SESSION</h2> <ol> <?php foreach ($_SESSION 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. .<hr/> <h2>$_POST</h2> <ol> <?php foreach ($_POST as $key => $item) { echo "<li><b>$key:</b> $item<br/></li>". In this exercise. We'll cover that in detail later in the course. } ?> </ol> <hr/> <h2>$_REQUEST</h2> <ol> <?php foreach ($_REQUEST as $key => $item) { echo "<li><b>$key:</b> $item<br/></li>".

which can be found at http://www. 3.w3schools. Test your solution in a browser.1. Create an associative array that holds your favorite colors indexed by their hex codes.com/html/html_colornames. For example. You can think of the outer array as containing the rows and the inner arrays as containing the data cells in those rows. After the existing table row.asp. 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. 2. Two-dimensional Arrays In PHP. write code to loop through the array outputting a table row with two columns for each element in the array. Open Arrays/Exercises/ColorTable2. two-dimensional arrays are arrays that contain arrays. 4. Rockband Beatles Rolling Stones Eagles Song1 Love Me Do Waiting on a Friend Song2 Hey Jude Angie Song3 Helter Skelter Yesterday's Papers Best of My Love Life in the Fast Hotel Lane California .php for editing.

'Waiting on a Friend'. column 2. array('Eagles'.'Life in the Fast Lane'. you need to nest one loop inside of another. Note that the header row is not included. 'Best of My Love') ) Reading from Two-dimensional Arrays To read an element from a two-dimensional array. 'Hey Jude'. Code Sample: Arrays/Demos/TwoDimensionalArrays.'Hotel California'. you must first identify the index of the "row" and then identify the index of the "column. Syntax <table border="1"> <?php foreach($Rockbands as $Rockband) { echo "<tr>".php <html> <head> <title>Two-dimensional Arrays</title> </head> <body> <h1>Two-Dimensional Arrays</h1> <?php . Syntax $Rockbands = array( array('Beatles'. the song "Angie" is in row 1. (see footnote) so it is identified as $Rockbands[1][2].'Angie'. } echo "</tr>".The following code creates this two-dimensional array. array('Rolling Stones'. The following code will create an HTML table from our two-dimensional array. } ?> </table> The above code snippets are combined in the following example to output a Rockbands table. foreach($Rockband as $item) { echo "<td>$item</td>". The internal arrays are highlighted." For example.'Love Me Do'. Looping through Two-dimensional Arrays To loop through a two-dimensional array.'Helter Skelter'). 'Yesterday\'s Papers').

The index association remains intact.'Helter Skelter'). Elements will be assigned to new index numbers. Reverse sorts an array alphabetically. array('Rolling Stones'. Elements will be assigned to new index numbers. Sorts associative arrays alphabetically by key. foreach($Rockband as $item) { echo "<td>$item</td>".'Waiting on a Friend'. The index .'Love Me Do'. array('Eagles'.'Hotel California'.'Life in the Fast Lane'. The index association remains intact. The index association remains intact. Reverse sorts associative arrays alphabetically by key. 'Hey Jude'. Sorts associative arrays alphabetically by value.'Yesterday\'s Papers'). Useful Array Functions (see footnote) Function sort() asort() ksort() rsort() arsort() krsort() Explanation Sorts an array alphabetically.$Rockbands = array( array('Beatles'. ?> <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>'. } echo '</tr>'. Reverse sorts associative arrays alphabetically by value. } ?> </table> </body> </html> Array Manipulation Functions The following table shows some of the more common array manipulation functions.'Angie'.'Best of My Love') ).

Useful Array Functions (see footnote) Function association remains intact. array_key_exis Checks to see if a specified key exists in an array. Takes one parameter and returns true or false depending on whether the parameter passed is an array. you will learn. There are two methods of submitting data through a form: the get method and the post method. 1. the random number generator needs to be seeded with rsand(). The . ) array_walk() count() explode() is_array() array_keys() Applies a user function to every element of an array. Explanation array_reverse( Returns an array with the elements in reverse order. To process form data with PHP. For the order to be sorted differently each time. shuffle() Randomly sorts the array. In this lesson. Returns all the keys of an associative array as an array. we have covered the most common uses of arrays... ts() Arrays Conclusion Arrays are an important feature of many modern programming languages. PHP and HTML Forms In this lesson of the PHP tutorial. Returns the number of elements in an array. Converts a string to an array by splitting it on a specified separator. HTML Forms How HTML Forms Work A very common way to pass data from one page to another is through HTML forms.

data is sent to the server in name-value pairs behind the scenes. can be uploaded via the form. 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.php"> <table> <tr> <td>First name:</td> <td><input type="text" name="FirstName" size="15"/></td> </tr> <tr> <td>Last name:</td> <td><input type="text" name="LastName" size="15"/></td> </tr> <tr> <td>Title:</td> <td><input type="text" name="Title" size="30"/></td> </tr> <tr> <td>Title of Courtesy:</td> <td> <input type="radio" name="TitleOfCourtesy" value="Dr. Post Method When the post method is used. such as images and Office documents. The default method is get. . The major disadvantage is that the resulting page cannot be bookmarked. Files.php <html> <head> <title>Add Employee</title> </head> <body> <h1>Add Employee</h1> <form method="post" action="ProcessEmployee. Code Sample: Forms/Demos/AddEmployee.method used is determined by the value of the method attribute of the form tag. The two major advantages of the post method are: • • The name-value pairs are not visible in the location bar. Get Method When the get method is used. A Sample HTML Form The following is a sample HTML form for inserting an employee record into a database. so sensitive data such as passwords are not displayed on the screen. data is sent to the server in name-value pairs as part of the query string. the page that is returned after the form is submitted)."/>Dr.e.

"/>Mrs. } ?> </select> <select name="BirthYear"> <?php for ($i=2006. $i=$i-1) { echo "<option value='$i'>$i</option>". </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."/>Mr. <input type="radio" name="TitleOfCourtesy" value="Mrs. $i++) { 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> ."/>Ms. $i<=31.<input type="radio" name="TitleOfCourtesy" value="Mr. <input type="radio" name="TitleOfCourtesy" value="Ms. $i>=1900.

$i>=1992.<select name="HireDay"> <?php for ($i=1. $i=$i-1) { echo "<option value='$i'>$i</option>". $i++) { echo "<option value='$i'>$i</option>". } ?> </select> </td> </tr> <tr> <td>Address:</td> <td><input type="text" name="Address" size="50"/></td> </tr> <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> <select name="HireYear"> <?php for ($i=2006. $i<=31.

If it is checked. <input type="submit" name="Inserting" value="Add Employee"/>). Select menus always send a variable to the server (unless they have been disabled in some way). when that submit button is clicked a variable by that name with the corresponding value will be sent to the server. no value is sent to the server.<select name="ReportsTo"> <option value="0">Choose. If a checkbox is not checked. the default value of "on" is sent unless otherwise set in the HTML. which contains some embedded PHP code. If the submit button has a name (e. Here are a few things you should know about how HTML forms are processed: 1. Form Variables Form variables are variables that are created when an HTML form is submitted using the post method. 5.php. the variable is sent to the server with a value of "" (empty string). Its action page is ProcessEmployee.g.. 4. If a text field or textarea is left blank. 2. If no radio button in a radio array is checked.</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. 3. no variable for that radio array is sent to the server.. outputs a simple HTML form. . which will eventually contain PHP code to process the submitted form. These variables are stored in the $_POST superglobal array.

Exercise: Processing Form Input Duration: 40 to 50 minutes. you will create a page that processes the form data. Filled out. is already complete and is identical to Demos/AddEmployee. The form entry page. the form would look like this: .php. Exercises/AddEmployee. In this exercise.php above.

the page should display as follows: .If everything is filled out correctly.

If all fields are left blank except for the password fields. the page should display as follows: . which contain two different values.

load Forms/Exercises/AddEmployee.. //The first one is done for you.. 2. which we'll worry about later).php <?php //For each entry coming through the form. ..either an error if the entry is not filled or filled incorrectly // .or the value entered. } else { $FirstName = $_POST['FirstName']. o or the value entered. 3. create a simple global variable to hold.</span>'.. if ($_POST['FirstName'] == '') { $FirstName = '<span style="color:red.php in the browser and fill out and submit the form. o either an error if the entry is not filled out or filled out incorrectly.1. 5.">First name omitted. Open Forms/Exercises/ProcessEmployee. To test your solution. Save your work. // create a simple global variable to hold. For each form entry (other than the dates.php in your editor. // . Output the variables as list items as shown in the screenshots above. Code Sample: Forms/Exercises/ProcessEmployee. 4.

include a form full of hidden fields containing the values entered and a submit button that reads "Confirm". //Part of the first one is done for you. make strings safe for outputting to the browser. 2. understand the benefits and dangers of magic quotes.. 4.. the concatenation operator is a dot (. Generally. Formatting Strings Concatenation Concatenation is a programming word for adding strings together. String Manipulation In this lesson of the PHP tutorial. work with string manipulation functions. In PHP. The example below illustrates this. To To To To format strings. If there are no errors. $Greeting = 'Hello'.} ?> <html> <head> <title>Process Employee</title> </head> <body> <h1>Process Employee</h1> <ul> <?php //Output the variables as list items. concatenation is used to combine literal text with variables or values returned from functions. you will learn.php <html> <head> <title>Concatenation</title> </head> <body> <h1>Concatenation</h1> <?php $FirstName = 'Paul'. 1. 3. . include a link at the bottom that directs the user to the form. echo "<li><b>Name:</b> $FirstName</li>". Code Sample: Strings/Demos/Concatenation. ?> </ul> </body> </html> If there are any errors.).

the function call must be outside of any quotes and combined with the rest of the string using the concatenation operator. $FirstName . date('l') . Presentation Function Description htmlentitie Escapes all HTML entities. ?> <h2>Using Double Quotes to Avoid the Concatenation Operator</h2> <?php echo "$Greeting $FirstName!". ) . '!'. ' ' . rtrim() Removes whitespace at the end of a string. ) strtolower( Converts a string to lowercase. s() nl2br() Inserts a <br /> tag before each newline character in a string. To do that. String Manipulation Functions Trimming Strings Functi on trim() ltrim() Description Removes whitespace at beginning and end of a string. This also is demonstrated in the code sample above. '. ' ' . but it does not work for concatenating values returned from functions. This works for concatenating literal strings with variables. strtoupper( Converts a string to uppercase. ?> <h2>Double quotes don't work when concatenating the results of a function call</h2> <?php echo $Greeting .echo $Greeting . $FirstName . double quotes can be used to avoid using the concatenation operator. ?> </body> </html> Code Explanation As shown in the code. Removes whitespace at the beginning of a string. '! Today is ' .'.

l Returns a len length substring beginning with the character in en) position pos.Returns a substring beginning with the character in position pos and len) chopping off the last len characters of the string.pos. placing a specified character or group of () characters between each array element.-len) Description Returns the substring from the character in position pos to the end of the string. Finds the position of the last occurrence of a specified character in a string. () implode Converts an array into a string. Converting Strings and Arrays Functi on Description explode Splits a string into an array on a specified character or group of characters.pos) substr(str. .. substr(str.pos. Returns the position of one string in another. Replaces all occurrences of one string with another string. Substrings Function substr(str. Finds the position of the first occurrence of a specified character in a string.Presentation Function ucfirst() ucwords() Description Converts the first character of a string to uppercase. Returns the substring from len characters from the end of the string to the end of the string. join() Same as implode(). strstr() stristr() strpos() strrpos() str_replace() Returns the position of one string in another. Case insensitive. Converts the first character of each word in a string to uppercase. substr(str.

> 0 if str1 is greater than str2. break.html">try again</a>. Examples of String Functions Below are some examples of string manipulation functions. Please <a href="Greeting. $Gender = strtolower(trim($_GET['Gender'])).Comparing Strings Function strcmp() Description Compares two strings. break. } } ?> </body> </html> . strcasecm Like strcmp() but case insensitive.'. Returns < 0 if str1 is less than str2. trim() and strtolower() This example uses trim() and strtolower() to improve the form validation script. default : echo "<b>$Gender</b> is not a gender!". $LastName!". if ($LastName == '' || $Gender == '') { echo 'Error: You must fill out the form. $LastName!". and 0 if they are equal. case 'female' : echo "Hello Ms.php <html> <head> <title>Greeting Page</title> </head> <body> <?php $LastName = trim($_GET['LastName']). } else { switch($Gender) { case 'male' : echo "Hello Mr. Code Sample: Strings/Demos/Greeting. p() strlen() Returns the length of a string.

htmlentities() and nl2br() (see footnote) The htmlentities() function is used to escape HTML entities. ?> </body> </html> This would result in the JavaScript code being executed. such as make a remote procedure call to execute a page on your server. Although this would be pretty annoying. Code Sample: Strings/Demos/HtmlEntitiesNotUsed. such as less than signs (<) and greater than signs (>). . You can test this by opening Strings/Demos/HtmlEntitiesNotUsed. Take a look at the screenshot below to get an idea of why this is important.php <html> <head> <title>HTML Entities Processor</title> </head> <body> <h1>HTML Entities Processor</h1> <?php echo $_POST['UserComments']. This JavaScript code would create a never-ending loop that popped up an alert over and over again. Imagine if this form were submitted to the script below. there are much worse things users could do.html and submitting the form. You probably don't want to test with a never-ending loop though.

<br /> while (true)<br /> {<br /> alert(&quot.This can easily be fixed by changing the code to look like this: Code Sample: Strings/Demos/HtmlEntitiesUsed.script language=&quot.<br /> .javascript&quot.php <html> <head> <title>HTML Entities Processor</title> </head> <body> <h1>HTML Entities Processor</h1> <?php echo nl2br(htmlentities($_POST['UserComments'])).Try to get rid of me!&quot. ?> </body> </html> This script uses htmlentities() to escape all the HTML entities and uses nl2br() to convert newline characters to breaks.&gt. 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> &lt.).

/script&gt. echo '<ol>'. trim($Email) . '</li>'.</body> </html> explode() The explode() function is used to convert a string to an array. } echo '</ol>'. This is because the string is exploded on the semi-colon only. foreach ($Emails as $Email) { echo '<li>' . the code of which is shown below. ?> </body> </html> Notice that the trim() function is used to trim the resulting elements of the array. The following form submits to Explode. that whitespace will be part of the array element.}<br /> &lt. .'. Code Sample: Strings/Demos/Explode. If the user adds additional whitespace around the semi-colon.php <html> <head> <title>Exploding Emails</title> </head> <body> <?php $Emails = explode('.php.$_POST['Emails']).

the substr() function behaves differently depending on the values passed to it. Open Strings/Exercises/ProcessEmployee. Modify the code so that hard returns in the Notes field are displayed in the output. 6.php in your editor. Fix it so that an error will be returned.php in the browser and fill out and submit the form. 5. 1. This does not result in an error. Where is the solution? Magic Quotes . 3.00" in the Password2 text box. The following screenshot shows the effects of using substr().substr() As shown earlier.php script you worked on earlier. Test the password comparison if condition by entering "0" in the Password1 text box and "-0. In this exercise. 2. To test your solution. 4. you will modify the ProcessEmployee. Exercise: Working with String Manipulation Functions Duration: 15 to 25 minutes. Modify the code so that each word of the employee's title begins with a capital letter. load Strings/Exercises/AddEmployee. Modify the code so that all leading and trailing whitespace is removed and HTML entities are escaped for all incoming form variables.

ini file that determine how PHP handles incoming data.). In this case. they can also cause confusion as the developer may not know whether magic quotes are turned on or off.g. and your script returned that value to the browser (e. To check whether they are on. the value returned would read "O\'Reilly".). } magic_quotes_runtime The value of magic_quotes_runtime determines whether data returned from files and databases should be escaped "automagically". you will learn.. double quotes and backslashes will be escaped with backslashes. Reusing Code and Writing Functions In this lesson of the PHP tutorial. echo stripslashes($_POST['LastName']). } else { echo $_POST['LastName']. magic_quotes_gpc The value of magic_quotes_gpc determines whether GET. to work with PHP's built-in string manipulation functions to improve form validation.g. POST and COOKIE data should be escaped "automagically". you have learned to format strings safely for outputting to the browser. echo $_POST['LastName']. You can easily escape a string when you need to with the addslashes() function.There are two settings in the php. Recommendation on Magic Quotes Our recommendation on magic quotes is to turn them off in the php. String Manipulation Conclusion In this lesson of the PHP tutorial. if (get_magic_quotes_gpc()) { echo stripslashes($_POST['LastName']). . then single quotes. Although magic quotes can be useful. It works similarly to magic_quotes_gpc. If magic_quotes_gpc is set to 1.. use the get_magic_quotes_gpc() function as shown below.ini file. if a user entered "O'Reilly" as her last name. You would need to strip the backslashes by passing the value through the stripslashes() function (e. and to understand how magic quotes work. The settings are magic_quotes_gpc (on by default) and magic_quotes_runtime (off by default).

All PHP code in the included file must be nested in PHP tags. require_once require_once can be used just like require. include only gives a warning. so require statements can be written in two ways: Syntax require(path_to_file). A Note on Security If included files are under the web root. The difference is that if the included file has already been included by earlier code. If the included file is a PHP file and a user navigates to it. With other extensions. Including Files PHP provides two common constructs for including files in web pages: require and include. Writing reusable code results in time and money savings. To write user-defined functions. If you need the included file to continue to process the page. the browser may attempt to download the file. As a precaution. they can be accessed just as any other file can. 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. and the ability to hide complex code from less seasoned developers. but a language construct. more consistent and bug free code. They are basically the same with one minor difference. This will prevent users from accessing the files directly. require path_to_file. path_to_file can be an absolute or a relative path. it will not be re-included. .1. To create a library of user-defined form-validation and form-entry functions. If they have an extension such as inc then the browser may display them as plain text. the server will try to process the file and may return errors. require require is not actually a function. To write reusable files and include them in multiple pages. 2. whereas. 3. you may want to place your included files in a directory above or outside of the web root. require throws a fatal error when it fails.

<hr/> <?php require 'Includes/Required. Code Sample: ReusingCode/Demos/Require. Add code to include Includes/Header. Open Includes/Header.php'. load ReusingCode/Exercises/index. Here is a code sample that demonstrates how to include files using require.php in the browser. which currently just contains a login form.php and Includes/Footer.php contains two included (required) files: Required. The extension of the included files does not affect how the code inside the files will be executed.php and Required. To test your solution.ini contains an include_path directive.inc.php and Includes/Footer.php <html> <head> <title>Including Files</title> </head> <body> This text is on the main page. you will add a header and a footer to a simple home page. 2. ?> <hr/> <?php require 'Includes/Required. 4. Notice that there is PHP code inside of Required. In this exercise.php in your editor and review the code. Exercise: Adding a Header and Footer Duration: 5 to 10 minutes. which takes a semi-colon delimited list of paths to directories that PHP should look in for included files. 1. which is executed. It should display as follows: . Require.include_path directive The php.inc'.inc. Open ReusingCode/Exercises/index. 3.php at the top and bottom or the page.php in your editor. ?> </body> </html> Code Explanation The above code is relatively straightforward.

inc" The auto_prepend_file directive can be used to application-wide variables such as database connection strings or common file paths. Automatically add files before or after any PHP document. contains settings for automatically prepending and appending files to every PHP script. auto_prepend_file = "c:/inetput/include/runbefore. . they contain no values. however. These settings are auto_prepend_file and auto_append_file.ini. Note that it is not possible to set different auto-prepend and auto-append files for different directories or different scripts.auto_prepend_file and auto_append_file The configuration file. php. By default. The auto_append_file directive can be used for cleaning up code or for outputting debugging information to the browser. they can be set to point to a files using absolute paths as follows: .inc" auto_append_file = "c:/inetput/include/runafter.

To define a function with parameters. Syntax function addNums($param1.php to see the above code in action. } Like built-in functions. do this other thing. Defining and Calling Functions A simple function is defined as follows. $param2. $param3) { $sum = $param1 + $param2 + $param3.User Functions User functions are used to make common tasks easier and to make code more modular and easier to read.3. } User functions can also return values. } User functions are called in the same way that built-in functions are. the following code calls the addNums() function to get the sum of three numbers. Unlike other identifiers in PHP. Syntax $total = addNums(1.5). functions are case insensitive. $param2. Syntax function addNums($param1. $sum. return $sum. do that. place receiving variables in the parentheses. echo 'The sum is ' . user functions can receive parameters. $param3) { $sum = $param1 + $param2 + $param3. See ReusingCode/Demos/SimpleUDF. . Syntax function myfunct() { do this. For example.

} $Total = addNums(1.php <html> <head> <title>Local Variables</title> </head> <body> <?php $a = 10. $param2=0.Default Values You can make function parameters optional by assigning default values to them as shown in the example below. if you don't pass a value into the function for one or more of the parameters. return $sum. echo $Total. the default value of 0 will be used. Variable Scope In PHP. The following code illustrates this: Code Sample: ReusingCode/Demos/LocalVars.php <html> <head> <title>Simple User-defined Function</title> </head> <body> <?php function addNums($param1=0. $param3=0) { $sum = $param1 + $param2 + $param3. $b = 5.3). } . ?> </body> </html> Code Explanation In this case. all required parameters should precede optional parameters. function incrNumBy() { $a += $b. variables declared outside of functions are not available by default inside of functions. Code Sample: ReusingCode/Demos/DefaultValues. When defining a function.

function incrNumBy($num. $a += $b. } incrNumBy(). they must be declared within the function as global variables using the global keyword. //results in two warnings as $a and $b are //undefined in the function scope echo $a.php <html> <head> <title>Global Variables</title> </head> <body> <?php $a = 10.incrNumBy(). By Value By default. . Code Sample: ReusingCode/Demos/GlobalVars. If the receiving variables are modified.php <html> <head> <title>By Value</title> </head> <body> <?php $a = 10. The following code illustrates this. function incrNumBy() { global $a.$b. echo $a. } incrNumBy($a.$b). //outputs 15 to the browser ?> </body> </html> By Reference vs. the passed variables remain unaffected. variables are passed to functions by value. $b = 5. //outputs 10 to the browser ?> </body> </html> To make the variables available to the function. meaning that the function's receiving variables get copies of the values received rather than pointers to them. Code Sample: ReusingCode/Demos/ByValue.$incr) { $num += $incr. $b = 5.

Code Sample: ReusingCode/Demos/ByReference. put an ampersand (&) before the parameter in the function definition. To pass a variable by reference. It's very easy to get your code all tangled up resulting in what is known as spaghetti code. . 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.echo $a. 4. 2. } incrNumBy($a. some are dependent on others. if errors are found when the form is submitted. it is nice to re-output the form. $a was unaffected by the function call. 3. For example. echo $a. We will now examine one approach for organizing code using functions and includes to make it easier to maintain. Writing code to output errors if there are any.$incr) { $num += $incr. any change in $num will affect $a.$b).php <html> <head> <title>By Reference</title> </head> <body> <?php $a = 10. So. Writing code to process the form entries if they are all valid. Although $num was incremented by 5. Writing validation code to validate the form entries after the form is submitted. Although these tasks are all separate. $b = 5. //outputs 10 to the browser ?> </body> </html> The above code outputs "10" to the browser. //outputs 15 to the browser ?> </body> </html> This time the function outputs "15" because $num references the variable $a itself. Form Processing Processing forms generally involves the following tasks: 1. function incrNumBy(&$num. Writing the HTML code to output the form.

Contains code to insert the employee into a database. Includes/fnStrings. If there are no errors. $MgrEntries[4]='Margaret Peacock'. When the user first visits.Contains a library of functions for presenting form fields. they will be displayed on the page. 2.php . 7. Includes/init.php . the user's entries will be displayed with a "Confirm" button.Code Organization Application Flow The application we are building works like this: 1. Includes/fnFormValidation. $MgrEntries[7]='Robert King'.) Includes/fnFormPresentation.php .Initializes and sets some variables. 6. $MgrEntries[8]='Laura Callahan'. We will examine each of these files.Contains a couple of useful string functions.Contains code to display entry form.php .. AddEmployee.. the data will be processed (e.Contains a library of functions for validating form entries. $MgrEntries[1]='Nancy Davolio'. If she fills out the form. 9. $MgrEntries[2]='Andrew Fuller'. entered into a database or emailed to someone). Includes/fnDates.php .Contains code to process the original form entry.php . $MgrEntries[5]='Steven Buchanan'.php . Code Sample: ReusingCode/Demos/Includes/init. o Correctly  She is presented with another form to confirm her entries.Contains a useful date function. $MgrEntries[3]='Janet Leverling'.Contains code that defines the flow of the application. .php <?php $ShowForm = true. Includes/EmployeeForm.g. she is presented with a form to fill out. If there are errors. (This file is currently empty.php . $MgrEntries = array(). o Incorrectly  She is presented with the same form with her entries in tact and appropriate error messages displayed. 8. Includes/InsertEmployee. we will organize it as follows: 1. 2.php . 5. 4. Application Files To make our code easier to maintain. 3. $MgrEntries[6]='Michael Suyama'. Includes/ProcessEmployee.  After confirming her entries.

'LastName'=>''.php'. 'HireYear'=>date('Y')). require 'Includes/init. 'Email'=>''. 'BirthYear'=>date('Y').php'. 'BirthMonth'=>1.$MgrEntries[9]='Anne Dodsworth'. 'Title'=>''. 'Extension'=>''. 'Password'=>''. 'PostalCode'=>''. Code Sample: ReusingCode/Demos/AddEmployee. if (array_key_exists('Submitted'. 'Country'=>''. $DbEntries = array( 'FirstName'=>''. $Errors = array(). 'Region'=>''. } elseif (array_key_exists('Confirmed'. require 'Includes/fnFormPresentation.php'.php'.Error {color:red. 'TitleOfCourtesy'=>''. require 'Includes/fnStrings.php'.$_POST)) . ?> Code Explanation This file sets several variables used throughout the application. require 'Includes/fnDates. ?> <html> <head> <title>Add Employee</title> <style type="text/css"> . 'HireMonth'=>1. 'Email'=>''.php'. 'ReportsTo'=>''. 'HireDay'=>1.} </style> </head> <body> <?php require 'Includes/Header.php <?php require 'Includes/fnFormValidation. $BrowserEntries = array(). 'HomePhone'=>''. 'Notes'=>''.php'. 'Address'=>''. 'BirthDay'=>1. 'City'=>''. font-size:smaller.$_POST)) { require 'Includes/ProcessEmployee.

$Months[] = 'March'.php'. we include several files we will need for the application. ?> </body> </html> Code Explanation The code is relatively easy to read. The form will be shown if:  it has not yet been submitted. form was submitted and includes the appropriate file. $Months[] = 'July'. if ($ShowForm) { require 'Includes/EmployeeForm. if either.php'. $Months[] = 'April'. $Months[] = 'May'. $Months[] = 'June'.{ } require 'Includes/InsertEmployee. $Months[] = 'February'. $Months[] = 'August'. $Months[] = 'October'. In the body. .php'. 2.php <?php /********* DATE FUNCTIONS *********/ /* Function Name: monthAsString Arguments: $m Returns: month as string */ function monthAsString($m) { $Months = array(). o code that checks which. $Months[] = 'November'. $Months[] = 'September'. $Months[] = 'January'. $Months[] = 'December'. we include: o our header and footer files. Code Sample: ReusingCode/Demos/Includes/fnDates. return $Months[$m-1]. o code that checks whether or not to show the main form. } require 'Includes/Footer. Things to note: 1.  it has been submitted with errors. At the very top.

2). } } ?> Code Explanation This file includes functions for cleaning up strings for browser and database output. } /* Function Name: dbString Arguments: $String Returns: trimmed and escaped string for database entry */ function dbString($Email) { if (get_magic_quotes_gpc()) { return trim ($Email).$Entries. } else { return addslashes(trim($Email)).} ?> Code Explanation This file includes a simple function for getting the name of a month (e.php <?php /********* FORM PRESENTATION FUNCTIONS *********/ /* Function Name: textEntry Arguments: $Display.g. February) given the month number (e.$Size? Returns: .php <?php /********** STRING FUNCTIONS *********/ /* Function Name: browserString Arguments: $String Returns: trimmed and escaped string for browser output */ function browserString($String) { return nl2br(trim(htmlentities($String))). Code Sample: ReusingCode/Demos/Includes/fnFormPresentation.$Errors.g.$Name. Code Sample: ReusingCode/Demos/Includes/fnStrings.

$Errors.= addErrorRow('Password'.$PW2. return $ReturnVal. } /* Function Name: pwEntry Arguments: $PW1.$Errors. } $ReturnVal .$Errors)) { $ReturnVal .$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>". } /* Function Name: textAreaEntry Arguments: $Display.$Entries. $Errors[$Name] .$Cols?. if (array_key_exists('Password'.= "</td> </tr>".= '<span class="Error" style="white-space:nowrap">* ' .$Errors.$Size? Returns: table rows as string */ function pwEntry($PW1.one table row as string */ function textEntry($Display.$Errors.$Rows? Returns: .$PW2. } return $ReturnVal. browserString($Entries[$Name]) .$Name.$Name.$Errors)) { $ReturnVal .$Entries. if (array_key_exists($Name.$Size=15) { $ReturnVal = " <tr> <td>$Display:</td> <td> <input type='text' name='$Name' size='$Size' value=\"" . '</span>'. "\">".$Errors).

$Name.$Errors.$Values Returns: table rows as string */ function radioEntry($Display.$Selected=0) { $ReturnVal = "<tr> <td>$Display:</td> <td> <select name='$Name'> <option value='0'>Choose one..$Errors)) { $ReturnVal .$Entries.= "</select> </td> </tr>".$Cols=45.$Options..$Values) { $ReturnVal = " <tr> <td>$Display:</td> <td>$Name</td> </tr>".= addErrorRow($Name.$Name. $ReturnVal .$Name.$Entries.= "</textarea> </td> </tr>".$Entries.$Name. } /* Function Name: radioEntry Arguments: $Display.</option>".= $Entries[$Name].$Errors).$Errors. } return $ReturnVal. .$Errors.$Selected? Returns: table rows as string */ function selectEntry($Display. } /* Function Name: selectEntry Arguments: $Display.$Rows=5) { $ReturnVal = " <tr> <td colspan='2'>$Display:</td> </tr> <tr> <td colspan='2'> <textarea name='$Name' cols='$Cols' rows='$Rows'>". $ReturnVal . if (array_key_exists($Name.$Entries. return $ReturnVal.$Errors. return $ReturnVal. $ReturnVal .table rows as string */ function textAreaEntry($Display.$Name.$Errors.

$Month.$Month. } $ReturnVal .= "<option value='$i' selected>". } else { $ReturnVal .$Year.} /* Function Name: selectDateEntry Arguments: $Display.= monthAsString($i) . } else { $ReturnVal .$NamePre.= "<option value='$i'>". } $ReturnVal .= "<option value='$i' selected>".$Day. $i<=12.= "$i</option>". $i++) { if ($i == $Month) { $ReturnVal . for ($i=date('Y').$Year Returns: table rows as string */ function selectDateEntry($Display. } $ReturnVal . "Month'>". $i++) { if ($i == $Day) { $ReturnVal . $i>=1900.= "$i</option>".= "</select> <select name='$NamePre" .= "</select> <select name='$NamePre" . for ($i=1.= '</select> </td> </tr>'.$Errors) { $ReturnVal = "<tr> <td>$Display:</td> <td> <select name='$NamePre" . . } $ReturnVal . "Day'>". "Year'>". } $ReturnVal .$NamePre. for ($i=1. $i<=31.= "<option value='$i' selected>". } $ReturnVal .$Day.= "<option value='$i'>". $i=$i-1) { if ($i == $Year) { $ReturnVal . } else { $ReturnVal . '</option>'.= "<option value='$i'>$i</option>".

return $ErrorRow. } return $ReturnVal.$Min?.$Trim=true) { if ($Trim) { $Text = trim($Text). but there are a couple that need to be finished.$Max?. This will be part of the next exercise. } if (strlen($Text) < $Min || strlen($Text) > $Max) { return false. $Errors[$Name] .$Errors) { $ErrorRow = '<tr><td colspan="2" class="Error">* ' .if (array_key_exists($NamePre . } return true. 'Date'.$Min=1.= addErrorRow($NamePre . '</td></tr>'. } ?> Code Explanation This file contains functions for presenting form entries. Several of these functions are complete. } /* . } /* Function Name: addErrorRow Arguments: $Name Returns: table row as string */ function addErrorRow($Name.php <?php /********* FORM VALIDATION FUNCTIONS *********/ /* Function Name: checkLength Arguments: $Text.$Errors)) { $ReturnVal . Code Sample: ReusingCode/Demos/Includes/fnFormValidation.$Trim? Returns: false if $Text has fewer than $Min characters false if $Text has more than $Max characters true otherwise */ function checkLength($Text. 'Date'.$Errors).$Max=10000.

25).'.$Errors. but there are a couple that need to be finished. echo selectDateEntry('Hire date'.$PW2) { return true.'Email'. $DbEntries['HireDay'].Function Name: checkEmail Arguments: $Email Returns: false if $Email has fewer than 6 false if $Email does not contain false if $Email does not contain false if the last @ symbol comes true otherwise */ function checkEmail($Email) { return true.'TitleOfCourtesy'.php <h1 align="center">Add Employee</h1> <form method="post" action="AddEmployee.) after the last period (.'Hire'.'Ms.'.$Errors.15). $DbEntries['BirthDay']. $DbEntries['HireYear'].) /* Function Name: checkPassword Arguments: $PW1.$DbEntries. } characters @ symbol a period (. $DbEntries['HireMonth'].'Birth'. This will also be part of the next exercise. Code Sample: ReusingCode/Demos/Includes/EmployeeForm. echo textEntry('Title'.'FirstName'. echo radioEntry('Title of Courtesy'. One of these functions is complete.15).30). $DbEntries['BirthMonth']. echo textEntry('Email'. echo textEntry('Last name'.'Title'.php"> <input type="hidden" name="Submitted" value="true"> <table align="center" border="1" width="500"> <?php echo textEntry('First name'. array('Dr.$Errors. echo selectDateEntry('Birth date'.'. .$DbEntries. } ?> Code Explanation This file contains functions for validating form entries.$DbEntries.')).$Errors.$Errors.'Mrs.'Mr.$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 */ function checkPassword($PW1. $Errors).'LastName'. $DbEntries. $DbEntries['BirthYear'].$DbEntries.

50.$DbEntries.$Errors. $DbEntries['Region'] = dbString($_POST['Region']). textEntry('City'.$MgrEntries. textAreaEntry('Notes'. $DbEntries['Title'] = ucwords(dbString($_POST['Title'])). textEntry('Address'. } else { . Code Sample: ReusingCode/Demos/Includes/ProcessEmployee. $DbEntries['LastName'] = dbString($_POST['LastName']).$Errors. textEntry('Country'. $Errors.50).$DbEntries. Notice that it creates entry rows through calls to functions in the fnFormPresentation.$DbEntries.'Extension'.10). $DbEntries['BirthDay'] = dbString($_POST['BirthDay']).30).$DbEntries.'ReportsTo'. $DbEntries['Notes'] = dbString($_POST['Notes']).$Errors). selectEntry('Manager'.$DbEntries. if (!checkLength($_POST['FirstName'])) { $Errors['FirstName'] = 'First name omitted.15).'Address'. $DbEntries['HomePhone'] = dbString($_POST['HomePhone']). ?> <tr> <td colspan="2"><input type="submit" value="Add Employee"></td> </tr> </table> </form> echo echo echo echo echo echo echo echo echo Code Explanation This file creates the entry form. textEntry('Home phone'. $DbEntries['PostalCode'] = dbString($_POST['PostalCode']).$Errors. $DbEntries['HireYear'] = dbString($_POST['HireYear']).3).'City'.'Region'. $DbEntries['Password'] = dbString($_POST['Password1']).5).$Errors. $DbEntries['Email'] = dbString($_POST['Email']).$Errors.$Errors. textEntry('Extension'. $DbEntries['Address'] = dbString($_POST['Address']).$DbEntries['ReportsTo']). This allows us to easily incorporate error handling and error messages into the form entries without making the HTML form itself difficult to maintain.$DbEntries. $DbEntries['BirthYear'] = dbString($_POST['BirthYear']).$DbEntries.'Notes'. textEntry('Postal Code'. $DbEntries['City'] = dbString($_POST['City']).$Errors.php file.'Password2'.$Errors.'.$DbEntries.'HomePhone'.2).5). $DbEntries['HireMonth'] = dbString($_POST['HireMonth']). echo pwEntry('Password1'.$Errors. textEntry('Region'. $DbEntries['Extension'] = dbString($_POST['Extension']).'Country'. $DbEntries['ReportsTo'] = $_POST['ReportsTo'].php <?php $DbEntries['FirstName'] = dbString($_POST['FirstName']).10). $DbEntries['Country'] = dbString($_POST['Country']).'PostalCode'. $DbEntries['HireDay'] = dbString($_POST['HireDay']). $DbEntries['BirthMonth'] = dbString($_POST['BirthMonth']).

'. } if (!checkLength($_POST['Address']. } if (!checkLength($_POST['Title'])) { $Errors['Title'] = 'Title omitted.'.5.$_POST['BirthYear'])) { $Errors['BirthDate'] = 'Birth date is not a valid date. } if (!checkdate($_POST['HireMonth'].$_POST['HireDay']. } else { $BrowserEntries['Address'] = browserString($_POST['Address']). } else { $BrowserEntries['Title'] = ucwords(browserString($_POST['Title'])). } else { $BrowserEntries['LastName'] = browserString($_POST['LastName']). } else { . } else { $Errors['TitleOfCourtesy'] = 'Title of Courtesy not selected.$_POST['BirthDay'].'. if (!checkLength($_POST['LastName'])) { $Errors['LastName'] = 'Last name omitted.'. } if ( array_key_exists('TitleOfCourtesy'.'. } if (!checkLength($_POST['City'].$_POST) ) { $BrowserEntries['TitleOfCourtesy'] = browserString($_POST['TitleOfCourtesy']).$_POST['HireYear'])) { $Errors['HireDate'] = 'Hire date is not a valid date.'. } if (!checkdate($_POST['BirthMonth'].100)) { $Errors['City'] = 'City omitted.} $BrowserEntries['FirstName'] = browserString($_POST['FirstName']). $DbEntries['TitleOfCourtesy'] = dbString($_POST['TitleOfCourtesy']).200)) { $Errors['Address'] = 'Address omitted.1.'.

0.">' . } if (!checkLength($_POST['PostalCode'])) { $Errors['PostalCode'] = 'Postal Code omitted. font-weight:normal">' . } if (!checkLength($_POST['Extension'].10. browserString(substr($_POST['Notes'].15)) { $Errors['HomePhone'] = 'Home phone must be between 10 and 15 characters. } if (!checkLength($_POST['HomePhone'].'.'. '</span><span style="color:red. } else { $BrowserEntries['PostalCode'] = browserString($_POST['PostalCode']). } if (!checkLength($_POST['Country'])) { $Errors['Country'] = 'Country omitted. font-weight:normal. } else { $BrowserEntries['Country'] = browserString($_POST['Country']). } else { $BrowserEntries['Extension'] = browserString($_POST['Extension']).'.0. } else { $BrowserEntries['Region'] = browserString($_POST['Region']).2) && !checkLength($_POST['Region'].0)) { $Errors['Region'] = 'Region name must be two characters.100)) .100)) .5)) { $Errors['Extension'] = 'Extension must be between 3 and 5 characters. if (!checkLength($_POST['Region']. browserString(substr($_POST['Notes'].100)) { $Errors['Notes'] = 'Notes must be fewer than 100 characters:<br/> <span style="color:blue.0.2.'. } if (!checkLength($_POST['Notes']. text-decoration:line-through. '</span>'.} $BrowserEntries['City'] = browserString($_POST['City']).'.3. . } else { $BrowserEntries['HomePhone'] = browserString($_POST['HomePhone']).

} ?> <?php if (!count($Errors)) { $ShowForm = false. } else { $BrowserEntries['Email'] = browserString($_POST['Email']). ?> <form method="post" action="AddEmployee.php"> <input type="hidden" name="Confirmed" value="true"> <?php echo '<h2>Confirm Entries</h2>'. foreach ($BrowserEntries as $key=>$Entry) { if ($key=='ReportsTo') { echo "<li><b>Manager:</b> $MgrEntries[$Entry]</li>". } if ( !checkPassword($_POST['Password1'].'.} else { $BrowserEntries['Notes'] = browserString($_POST['Notes']). } if ( !checkEmail($_POST['Email']) ) { $Errors['Email'] = 'Email is invalid. foreach ($DbEntries as $key=>$Entry) . } else { echo "<li><b>$key:</b> $Entry</li>".'. } else { $BrowserEntries['ReportsTo'] = $_POST['ReportsTo']. } if ($_POST['ReportsTo'] == 0) { $Errors['ReportsTo'] = 'Manager not selected. } } echo '</ol>'.$_POST['Password2']) ) { $Errors['Password'] = 'Passwords do not match or are not the right length. echo '<ol>'. } else { $BrowserEntries['Password'] = browserString($_POST['Password1']).'.

If there are errors.php file for validating entries. 3. you will complete several functions needed for the application we have just seen. so that the original form will not be displayed and it outputs all the entries (made browser-safe) to the browser for confirmation.php in your browser and submit the form several times entering different data combinations each time. } ?> Code Explanation This file contains code for processing the form entries. open ReusingCode/Exercises/AddEmployee. 2. Open ReusingCode/Exercises/Includes/fnFormValidation. If errors are found. it sets the boolean $ShowForm to false.php in your editor. Code Sample: ReusingCode/Demos/Includes/InsertEmployee.{ ?> <input type="hidden" name="<?php echo $key ?>" value="<?php echo $Entry ?>"> <?php } ?> <input type="submit" value="Confirm"> </form> <?php } else { $DbEntries = $_POST. Complete the radioEntry() and selectEntry() functions so that the return value contains correct form entries and. errors. which is passed into the form presentation functions. Open ReusingCode/Exercises/Includes/fnFormPresentation. 5. Exercise: Form Validation and Presentation Functions Duration: 45 to 60 minutes. . the boolean $ShowForm is left as true. so that they can return code for displaying the errors. if appropriate. In this exercise. so that they return true if the form entry is valid and false otherwise. it adds them to the $Errors array. so that the original form is redisplayed. It makes use of functions in the fnFormValidation.php TO DO LATER Code Explanation This file will eventually contain code for inserting the employee information into the database. To test your solution. 4.php in your editor. If no errors are found. Complete checkEmail() and checkPassword(). 1.

2. Free up resources and disconnect from the database. Connect to the database. Querying a Database The steps for querying a database in a PHP script are as follows: 1.'Northwind'). you will learn. . To update existing records in a database.3 and above and takes advantage of a new faster connection protocol in MySQL. $Result = $DB->query($Query).php <html> <head> <title>Simple Query . Send query to the database. mysqli_connect_error(). 1. if (mysqli_connect_errno()) { echo 'Cannot connect to database: ' .'pwdpwd'. which works with MySQL versions 4.OO</title> </head> <body> <?php @$DB = new mysqli('localhost'. mysqli() Overview New in PHP5 is the mysqli library. Output the results of the query to the browser. To insert new records into a database. 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. 3. Code Sample: ManagingData/Demos/SimpleQuery-OO. $NumResults = $Result->num_rows. } else { $Query = 'SELECT * FROM Employees'.1.. To retrieve and safely display records from a database. 4.Managing Data In this lesson of the PHP tutorial. Retrieve and store results sent back from the database. 3. 5.'root'. 2..

$Row['FirstName'] . echo '<td>' .'pwdpwd'. echo '</tr>'. $Row['Extension'] . '</td>'. '</td>'. $NumResults = mysqli_num_rows($Result). '</td>'.$Query). echo "<b>$NumResults Employees</b>". $Row['LastName'] .echo "<b>$NumResults Employees</b>". } ?> </table> <?php $Result->free(). ?> <table border="1"> <tr> <th>First Name</th> <th>Last Name</th> <th>Title</th> <th>Email</th> <th>Extension</th> </tr> <?php while ($Row = $Result->fetch_assoc()) { echo '<tr>'.'Northwind'). '</td>'. '</td>'. } else { $Query = 'SELECT * FROM Employees'. echo '<td>' . $DB->close().php <html> <head> <title>Simple Query . if (mysqli_connect_errno()) { echo 'Cannot connect to database: ' .Procedural</title> </head> <body> <?php @$DB = mysqli_connect('localhost'. echo '<td>' . echo '<td align="right">x' . } ?> </body> </html> Code Sample: ManagingData/Demos/SimpleQueryProcedural. $Result = mysqli_query($DB. ?> <table border="1"> <tr> <th>First Name</th> . $Row['Email'] . $Row['Title'] .'root'. echo '<td>' . mysqli_connect_error().

'</td>'. '</td>'. "</td>". mysqli_close($DB). o o Procedural: @$DB = mysqli_connect('localhost'. $Row['Extension'] . echo "<td>" . we use: (see footnote) 1. "</td>". '</td>'. echo '</tr>'. which returns an error number if there is a connection error or 0 if there is no error. o Procedural: $Result = mysqli_query($DB.$Query). echo '<td>' .'root'.'pwdpwd'. To see if the connection was successful we check mysqli_connect_errno(). } ?> </body> </html> Code Explanation 1. To connect to the database. $Row['LastName'] . echo '<td>' . To send the query to the database and store the results in a variable. '</td>'. echo '<td>' . 2. $Row['LastName'] .'pwdpwd'.'Northwind'). We use the procedural interface in both cases. we use: o Object-oriented: o o o o o while ($Row = $Result->fetch_assoc()) { echo "<tr>". 3. echo '<td align="right">x' . $Row['Email'] . Object-oriented @$DB = new mysqli('localhost'. we use: o Object-oriented: $Result = $DB->query($Query).<th>Last Name</th> <th>Title</th> <th>Email</th> <th>Extension</th> </tr> <?php while ($Row = mysqli_fetch_assoc($Result)) { echo '<tr>'. $Row['Title'] . To output the results of the query. If an error occurs. we output a message with mysqli_connect_error(). 4. '</td>'. because a connection object doesn't get created if the connection fails. echo "<td>" . echo '<td>' . $Row['FirstName'] . } ?> </table> <?php mysqli_free_result($Result). $Row['FirstName'] .'Northwind'). .'root'.

$Row['Title'] . mysqli_close($DB). echo "</tr>". "</td>". "<td>" . "</td>". "</td>". mysqli_connect_err Returns connection error message. new mysqli() mysqli_connect() mysqli_connect_err Returns connection error number or 0 if no() there's no error. $Row['Email'] . "</td>". or() $DB>host_info mysqli_get_host_inf Returns information on the connection. } 5. the two scripts are pretty similar. echo "<td>" . We will use the object-oriented interface in future examples. $Row['FirstName'] .o o o o } o o o o o o o o o o echo echo echo echo "<td>" . "<td align='right'>x" . o() . $Row['Title'] . "</td>". To free up resources and disconnect from the database. echo "<td>" . $Row['LastName'] . $DB->close(). Procedural: while ($Row = mysqli_fetch_assoc($Result)) { echo "<tr>". echo "<td>" . mysqli Methods and Properties Connection Methods and Properties Objectoriented Procedural Description Connects to a MySQL server. echo "<td align='right'>x" . "</td>". echo "<td>" . $Row['Extension'] . "</td>". o o Procedural: mysqli_free_result($Result). we use: o Object-oriented: o $Result->free(). "</td>". $Row['Email'] . $Row['Extension'] . "</tr>". As you can see.

mysqli_fetch_obje Returns a result row from a query result object ct() or resource as an object.php ---. echo '<td>' . $Row['FirstName'] . . Review the following scripts. '</td>'. $Row['Title'] . $Row['Extension'] . Fetch Functions Objectoriented $Result>fetch_row() $Result>fetch_assoc() $Result>fetch_object() Procedural Description mysqli_fetch_row Returns a result row from a query result object () or resource as an indexed array. '</td>'. echo '<td>' .Code Omitted ---<table border="1"> <tr> <th>First Name</th> <th>Last Name</th> <th>Title</th> <th>Email</th> <th>Extension</th> <th>Edit</th> </tr> <?php while ($Row = $Result->fetch_assoc()) { echo '<tr>'. echo '<td align="right">x' . '</td>'. '</td>'. $Row['Email'] . '</td>'. Inserting and Updating Records Records are inserted and updated with SQL queries using the same mysqli library we used to generate a report. mysqli_fetch_ass Returns a result row from a query result object oc() or resource as an associative array. echo '<td>' . $Row['LastName'] . Code Sample: ManagingData/Demos/EmployeeReport. echo '<td>' .Query Functions Objectoriented $DB->query() Procedural mysqli_query() Description Sends a query to the database and returns results. $DBmysqli_multi_que Sends multiple queries to the database and >multi_query() ry() returns results.

mysqli_connect_error().$_POST)) { require 'Includes/ProcessEmployee. $Row['EmployeeID'] .php'.php'.php'.php'. Code Sample: ManagingData/Demos/EditEmployee.php'. font-size:smaller. } ?> <html> <head> <title>Edit Employee</title> <style type="text/css"> . '"/> <input type="submit" name="Editing" value="Edit"/> </form></td>'. require 'Includes/fnStrings. if (mysqli_connect_errno()) { echo 'Cannot connect to database: ' . ?> </body> </html> .php'.echo '<td><form method="post" action="EditEmployee.php'. echo '</tr>'.php.Error {color:red.php"> <input type="hidden" name="EmployeeID" value="' . require 'Includes/EmployeeForm. $DB->close().php'. if (array_key_exists('Updating'. } ?> </table> ---. require 'Includes/fnFormPresentation.php'.Code Omitted ---- Code Explanation This file is similar to the SimpleQuery examples we saw earlier in this lesson.'Northwind'). require 'Includes/init.php <?php require 'Includes/fnFormValidation. require 'Includes/fnDates.php'.'root'.} </style> </head> <body> <?php require 'Includes/Header. The only difference is that each row now has an edit form in the last column. } require 'Includes/EmployeeData. which sends the employee's EmployeeID to EditEmployee. require 'Includes/Footer.'pwdpwd'. @$DB = new mysqli('localhost'.

MONTH(BirthDate) AS BirthMonth. if so. Extension. 2.php <?php /********** STRING FUNCTIONS *********/ ---. City. includes the processing file. This one goes a step further though by connecting to the database to retrieve data to populate the form. TitleOfCourtesy. YEAR(HireDate) AS HireYear. Notes. we include several files we will need for the application and we connect to the database. DAYOFMONTH(HireDate) AS HireDay. HomePhone. Password FROM Employees WHERE EmployeeID = $EmployeeID". $Result->free(). Region. $Result = $DB->query($Query). Email.Code Explanation This file is similar to the AddEmployee. o code that checks whether the user has already made updates and. Country.Code Omitted ---/* Function Name: dbString Arguments: $String Returns: . $DbEntries = $Result->fetch_assoc(). LastName. MONTH(HireDate) AS HireMonth. Title. ?> Code Explanation This file contains the query that selects the specified employee's data and populates the $DbEntries array with the results. At the very top. In the body. Code Sample: ManagingData/Demos/Includes/fnStrings.php file we worked on earlier in the course. DAYOFMONTH(BirthDate) AS BirthDay. It works as follows: 1. we include: o our header and footer files. PostalCode. Code Sample: ManagingData/Demos/Includes/EmployeeData. Address. ReportsTo. $Query = "SELECT FirstName. YEAR(BirthDate) AS BirthYear.php <?php $EmployeeID = $_POST['EmployeeID']. o the file with code to retrieve the specified employee's data. o the file with code to display the filled-in form.

12) && strcmp($PW1. If they are not. Code Sample: ManagingData/Demos/Includes/fnFormValidation. then form entries will be made database-safe "automagically".$PW2) == 0.$CheckLength? 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 */ function checkPassword($PW1. $PW2 = trim($PW2). so it just returns the trimmed string.trimmed and escaped string for database entry */ function dbString($String) { $String=trim($String).Code Omitted ---/* Function Name: checkPassword Arguments: $PW1. If they are.$PW2. then it uses addslashes() to make the string safe for database queries. It now checks to see if magic quotes are turned on.$PW2.php <?php /********* FORM VALIDATION FUNCTIONS *********/ ---.$CheckLen=true) { $PW1 = trim($PW1). } else { return addslashes($String). } } ?> Code Explanation This file is the same as the fnStrings. } } ?> Code Explanation . } else { return strcmp($PW1.6.$PW2) == 0. if ($CheckLen) { return checkLength($PW1.php file we saw before except that the dbString() function has been updated. if (get_magic_quotes_gpc()) { return $String.

Code Omitted ---?> <?php if (!count($Errors) && array_key_exists('EmployeeID'.php file we saw before except that the checkPassword() function now takes an additional parameter: $CheckLen.$_POST)) { $PwCheckLen = false. which when set to false. $DbEntries['City'] . $DbEntries['Address'] . $DbEntries['LastName'] . Region='" . '-' . Code Sample: ManagingData/Demos/Includes/ProcessEmployee. '-' . BirthDate='" . will prevent the function from returning false if a blank password is entered. $DbEntries['Country'] . $DbEntries['PostalCode'] . $DbEntries['TitleOfCourtesy'] .$PwCheckLen) ) { $Errors['Password'] = 'Passwords do not match or are not the right length. $Query = "UPDATE Employees SET FirstName='" . $DbEntries['Title'] .This file is the same as the fnFormValidation. Address='" . HireDate='" . ---.$_POST)) { $EmployeeID = $_POST['EmployeeID']. $DbEntries['FirstName'] . "'.Code Omitted ---if (array_key_exists('EmployeeID'. Country='" . Email='" . "'. } else { $PwCheckLen = true. "'. $DbEntries['Region'] . $DbEntries['HireYear'] . "'. $DbEntries['BirthYear'] . "'. $DbEntries['Email'] . PostalCode='" . . "'. "'. $DbEntries['BirthMonth'] . $DbEntries['HireMonth'] . "'.php <?php $DbEntries = $_POST.$_POST['Password2']. '-' . "'.'. '-' . "'. "'. "'. } if ( !checkPassword($_POST['Password1']. TitleOfCourtesy='" . City='" . Title='" . LastName='" . $DbEntries['HireDay'] . $DbEntries['BirthDay'] . foreach ($DbEntries as &$Entry) { $Entry = dbString($Entry). } $DbEntries['Title'] = ucwords($DbEntries['Title']). } else { $BrowserEntries['Password'] = browserString($_POST['Password1']). } ---.

= " WHERE EmployeeID = $EmployeeID". Open ManagingData/Exercises/InsertEmployee. We only want to check the password length for new entries. Password='" . If the EmployeeID key exists in the $_POST array. $DbEntries['ReportsTo']. then the Edit Employee form has been submitted and a database query will be executed to update the employee record. } ?> HomePhone='" . "'. Code Explanation This file is the same as the ProcessEmployee. $DbEntries['HomePhone'] .Code Omitted ---} else { $DbEntries = $_POST. } $Query .php script to insert new employees. ?> ---. if (CheckLength($DbEntries['Password'])) { $Query .php for editing. 3.} elseif (!count($Errors)) { $ShowForm = false. $DbEntries['Password'] . Write code to execute the query. you will work on the InsertEmployee. 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. Notes='" . $DB->query($Query). 2. echo '<div align="center">Record Updated</div>'. Extension='" . "'". . In this exercise. Exercise: Inserting Records Duration: 30 to 40 minutes. 2. $DbEntries['Extension'] . 1. 5.php file we saw before with a few important changes: 1. "'. 3. ReportsTo=" . Make the connection to the database.= ". The SQL insert query has been started for you. "'. Instead of assigning values from $_POST to $DbEntries one by one. Add code at the top to populate $DbEntries with SQL-safe entries from the form. we simply copy $_POST into $DbEntries and then loop through the array to pass each element through dbString(). not for updates. 4. $DbEntries['Notes'] . Finish it. Notice the use of the & to make $Entry a reference to rather than a copy of the array element.

return "Employee Added" and a link to EmployeeReport. HireDate. so that the user can enter another employee..php.o o If the query succeeds. Password). which improve performance and improve security. //Execute the query. Where is the solution? mysqli Prepared Statements With mysqli it is possible to create prepared statements.'root'. look at the following example. ReportsTo. BirthDate. //Connect to the database //Finish the query below $Query = "INSERT INTO Employees (FirstName. HomePhone.php <html> <head> <title>Prepared Statement</title> </head> <body> <?php $CompanyID = $_GET['City'].. return 'Insert failed' ?> Instead of hiding the form after an employee is inserted. Email.'Northwind'). Prepared statements are essentially templated queries to which you can bind input and output variables. if (mysqli_connect_errno()) { .php <?php //Add code to populate $DbEntries with //SQL-safe entries from the form. //Try London @$DB = new mysqli('localhost'. return 'Employee Added' // and provide a link to EmployeeReport. Notes. You will also need to set $ShowForm to false to prevent the form from reappearing. PostalCode. (see footnote) Code Sample: ManagingData/Demos/PreparedStatement. return "Insert failed". TitleOfCourtesy.'pwdpwd'.php // and set $ShowForm to false //If it fails. Extension. Title. If the query fails. //If the query succeeds. LastName. Code Sample: ManagingData/Exercises/Includes/InsertEmployee. Provide a new empty form. Region. City. Address. Country. To illustrate.

which takes a query as an argument. The statement is executed with the execute() method. $DB->close(). and double.Phone FROM Customers WHERE City=?'. If the query returns results (e. A statement is prepared using the prepare() method. The character specifies the data type of that input parameter. 2.$CompanyID).echo 'Cannot connect to database: ' . ?> <table border="1"> <tr> <th>Company</th> <th>Contact</th> <th>Phone</th> </tr> <?php while ($Stmt->fetch()) { echo '<tr>'. A query is created with question marks used as placeholders for parameters (input variables). . $Stmt->bind_result($Company.g. echo "<td>$Company</td>". $Stmt = $DB->prepare($Query). The fetch() method can be used to fetch rows from the result set. For example. the process is as follows: 1. "isd" would specify that the input parameters are an integer. $Stmt->bind_param('s'.ContactName. in that order. echo '</tr>'. Parameters can be bound to the statement with the bind_param() method. } else { $Query = 'SELECT CompanyName. SELECT queries). 6. The first argument of this method is a string that has one character for each subsequent argument. mysqli_connect_error(). echo "<td>$Phone</td>". echo "<td>$Contact</td>". string.$Phone). $Stmt->execute(). The only other option is b for blob.$Contact. 5. 3. } ?> </table> <?php $Stmt->close(). } ?> </body> </html> Code Explanation Using the object-oriented interface. they can be bound to the statement with the bind_result() method. 4.

Prepared statements are most useful in cases where you have to loop through a dataset to do bulk inserts or updates.
Prepare Functions Object-oriented $db->prepare() $Stmt>bind_result() $Stmt>bind_param() $Stmt>execute() $Stmt->fetch() $Stmt->close() Procedural mysqli_prepare() Description Prepares a SQL statement for execution.

mysqli_stmt_bind_res Binds variables to a prepared ult() statement results. mysqli_stmt_bind_par Binds variables to a prepared am() statement. mysqli_stmt_execute( Executes a prepared statement. ) mysqli_stmt_fetch() mysqli_stmt_close() Fetches results into the bound variables. Closes prepared statement.

PEAR:DB
In this lesson of the PHP tutorial, you will learn... 1. To use the PEAR DB package as a database abstraction layer.

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.

Advantages and Disadvantages of PEAR DB
Whether or not you decide to use PEAR DB or a similar database abstraction layer depends on your needs. If you need to be able to work on many applications and get your work done quickly, then PEAR DB is certainly helpful. If performance is key, then you may find the extra weight of PEAR DB to be prohibitive.

Why use a database abstraction layer?
One big benefit of using a database abstraction layer like PEAR DB is portability. PEAR DB allows you to use a single API for working with many different types of databases. So if you decide to move to another database, you will not have to rewrite all your code. Another benefit is code simplification. If your application involves multiple databases of different flavors or you work on many applications each of which uses a different type of database, you would normally have to learn the APIs for each of the databases you would be working with. Again, PEAR DB allows you to work with all these databases using the same API.

When not to use a database abstraction layer?
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

Some of the drivers supported by PEAR DB are
• • • • • • • • •

mysqli myssql mssql oci8 odbc pgsql sybase dbase sqlite

Code Sample: PEAR-DB/Demos/EmployeeReport.php
<html> <head> <title>Employee Report</title> </head> <body> <?php require_once 'DB.php';

@$DB = DB::connect('mysqli://root:pwdpwd@localhost/Northwind'); if (DB::isError($DB)) { echo 'Cannot connect to database: ' . $DB->getMessage(); } else { $Query = 'SELECT * FROM Employees'; $Result = $DB->query($Query); $NumResults = $Result->numRows(); echo "<b>$NumResults Employees</b>"; ?> <table border="1"> <tr> <th>First Name</th> <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:

'</td>'. 16. 18. '<td>' . respectively. we connect to the database: o @$DB = DB::connect('mysqli://root:pwdpwd@localhost/Northwind'). '<td>' . Other options are DB_FETCHMODE_ORDERED (the default) and DB_FETCHMODE_OBJECT. '</td>'. 10. 14. after writing out our header row.ini includes a path to the pear folder containing DB. The :: syntax will be covered when we discuss object-oriented PHP programming. $Row['Email'] . we loop through the query results outputting a row for each record returned: 11.php itself includes files. '<td>' . if (DB::isError($DB)) 5. '<td>' . so it can be called without first instantiating an object. but the crux of it is that the connect() method is a class-level method rather than an object-level method. 15. '</td>'. we run our query: 8. $Row['LastName'] .php. 2. which would mean that the connection failed. $Row['FirstName'] . $DB->getMessage(). In this example. Next. } while { echo echo echo echo echo echo ($Row = $Result->fetchRow(DB_FETCHMODE_ASSOC)) '<tr>'. '<td align="right">x' . we output an error. echo 'Cannot connect to database: ' . } 7. $Result = $DB->query($Query).php is in the same directory as EmployeeReport.php. '</td>'. Exercise: Creating a Customer Report Duration: 20 to 30 minutes. . We then use the class-level isError() method to check if $DB is an error object. 9. 17. (see footnote) 3.DB. If it did fail. 4. '</td>'. 12. we use DB_FETCHMODE_ASSOC to get the row as an associative array.And. The fetchRow() method can take one of several constants to specify how a row is returned. o The include_path directive in php. 13. { 6. This isn't likely as DB. If the connection succeeded. $Query = 'SELECT * FROM Employees'. which get the row as an indexed array and an object. This line of code will create a connection object if the connection is successful or an error object if it is not. $NumResults = $Result->numRows(). $Row['Title'] . $Row['Extension'] . which would also have to be in the same directory.

the query below would return 10 orders starting with the 100th order (note that the first row is row 0). 2. o Output the results of the query in a table. OrderID FROM Orders LIMIT 99. Code Sample: PEAR-DB/Exercises/SalesReport. // If the connection fails. Open PEAR-DB/Exercises/SalesReport.In this exercise. Order by OrderDate. // 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. This is two many to display on a single page. ?> <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. Write code to: o Include the PEAR DB package. } ?> </body> </html> 830 rows are returned. o Connect to the Northwind database. SELECT OrderDate.php for editing. return an error message to the browser. return an error message to the browser. MySQL has a LIMIT clause that specifies which and how many records to return from the query. o If the connection fails. For example. ?> </table> <?php //Free the result and disconnect from the database.10. 1. . o If the connection 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.php <html> <head> <title>Sales Report</title> </head> <body> <?php //Include PEAR DB Package //Connect to the Northwind database. you will create a sales report using PEAR DB. o Free the result and disconnect from the database. Order by OrderDate.

$_POST)) { $Email = $_POST['Email']. $PW = $_POST['Password'].. 1. $msg=''. you will learn.. } } if (!array_key_exists('LoggingIn'.php <html> <head> <title>Login Page</title> </head> <body> <?php require 'Includes/Header. if ($Email == 'jwayne@northwind.php"> <input type="hidden" name="LoggingIn" value="true"> <table> <tr> <td>Email:</td> . unset($_POST['LoggingIn']). $Email = ''. Authentication with PHP and SQL In this lesson of the PHP tutorial.$_POST)) { ?> <div align="center"> <h2>Log in</h2> <form method="post" action="SimpleLogin.com' && $PW == 'cowboy') { echo '<div align="center">Success</div>'. Code Sample: Authentication/Demos/SimpleLogin. A Database-less Login Form Below is a simple login form that uses a hard-coded username and password. } else { echo '<div align="center">Login Failed</div>'. if (array_key_exists('LoggingIn'.Add code to your solution that allows the user to tab through the results 10 at a time with Previous and Next buttons. To authenticate users with a login form.php'.

it outputs a "failed" message and removes LoggingIn from the $_POST array. so that the form will be displayed again. . If they don't. } else { echo '<div align="center">Login Failed</div>'. Exercise: Authenticating Users Duration: 25 to 35 minutes. if ($Email == 'jwayne@northwind. $PW = $_POST['Password']. A hidden field.php'. If it does.e. it outputs a "success" message. is passed to the server when the user submits the form. } This code simply checks to see if the user's email and password match the hard-coded values (jwayne@northwind.com' && $PW == 'cowboy') { echo '<div align="center">Success</div>'. ?> </body> </html> Code Explanation This page contains an HTML login form. unset($_POST['LoggingIn']).<td><input type="text" name="Email" value="<?php echo $Email?>" size="25"></td> </tr> <tr> <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. The script checks to see if LoggingIn exists in the $_POST array. If they do. In this exercise.com and cowboy). which submits to itself (i. it processes the form input: $Email = $_POST['Email']. you will use mysqli or PEAR DB to authenticate users. the action points to the same page). LoggingIn.

php when creating LoginForm. you will learn.php in your editor.php'.php'.php and to ManagingData/Demos/Includes/ProcessEmployee. You will see that it includes several of the scripts we saw in earlier exercises. if (array_key_exists('LoggingIn'.php. require 'Includes/fnStrings. } if (!array_key_exists('LoggingIn'. 'Password'=>'').php when creating Login.1. Code Sample: Authentication/Exercises/index. ?> <html> <head> <title>Northwind Home Page</title> </head> <body> <?php $msg=''. It now takes a fifth parameter: $Repeat.. ?> </body> </html> Regular Expressions In this lesson of the PHP tutorial.php'. You may find it helpful to refer to ManagingData/Demos/Includes/EmployeeForm. 2. When $Repeat is set to false. $Errors = array(). require 'Includes/Header. } if (strlen($msg) > 0) { echo "<div align='center'>$msg</div>".. } require 'Includes/Footer. she'll just get a single password field (used for login forms).php'. but a small change has been made to the pwEntry() function in Authentication/Exercises/Includes/fnFormPresentation.php and Authentication/Exercises/Includes/Login.php. This file has been created for you and contains the underlying logic of the authentication application.php. Your job is to finish Authentication/Exercises/Includes/LoginForm. When $Repeat is set to true (default). . Open Authentication/Exercises/index.php <?php require 'Includes/fnFormPresentation.php'. which are currently both nearly empty. the user will be asked to repeat her password (used for registration forms). $DbEntries = array( 'Email'=>''.$_POST)) { require 'Includes/Login. Most of these are exactly the same.php'.$_POST)) { require 'Includes/LoginForm.

Regular expressions are used to do sophisticated pattern matching. preg_match() returns 1 if pattern is found in text_to_search and 0 if it is not. @$TextToSearch = $_POST['TextToSearch'].php <?php @$Pattern = $_POST['Pattern']. The code for the tester is shown below. font-size: 14pt. ?> <html> <head> <title>Regular Expression Tester</title> <style> . padding: 2px} </style> <script> . Perl-compatible Regular Expression Functions preg_match() The syntax for preg_match() is as follows. so we'll cover these in this class. 2.1.reg {font-family:Verdana. padding: 4px} . preg_replace() replaces all instances of pattern in text_to_search with replacement. color:darkblue.reg:hover {border: 2px solid red. replacement. To use regular expressions for advanced form validation. To understand how regular expressions work. preg_replace(pattern. preg_replace() The syntax for preg_replace() is as follows. preg_match(pattern. Regular Expression Tester We have created a simple PHP-based regular expression tester. The Perl style is more powerful and much more common. Code Sample: RegExp/Demos/Tester. font-weight:bold. text_to_search). text-decoration:none. PHP supports two types of regular expressions: POSIX and Perl. text_to_search).

[a-zA-Z0-9\\-\\.]?[0-9] {4}$/')." class="reg">SSN</a></th> . Helvetica." class="reg">Email</a></th> <th><a href="javascript:usePattern('/^[0-9]{3}[\\. sans-serif. sans-serif">Text to search:</font></td> <td><font size="+3" face="Arial.innerHTML="<b>PATTERN: </b>" + PATTERN.]?[0-9]{2}[\\. sans-serif"> <input type="text" name="Pattern" size="50" value="<?= $Pattern ?>" maxlength="100"> </font></td> </tr> <tr> <td colspan="2" align="center" style="font-size:18pt. document. elseif (preg_match($Pattern. Helvetica. Helvetica. Helvetica. else echo '<font color="red">No Match</font>'. } </script> </head> <body> <h2><font face="Verdana. Arial. sans-serif" id="exp">Pattern:</font></td> <td><font size="+3" face="Arial. sans-serif">Regular Expression Tester</font></h2> <form name="formRE" method="post"> <table> <tr> <td align="right"><font size="+2" face="Arial.]+@[a-zA-Z0-9\\-] +\\. Helvetica.value=PATTERN. ?> </td> </tr> <tr align="center"> <td colspan="2"><font size="+2" face="Arial. font-family:Arial. Helvetica. Helvetica. background: #cccccc.getElementById("display").Pattern.]+$/').formRE."> <?php if (empty($Pattern)) echo '<font color="blue">Let\'s play!</font>'. sans-serif"> <input type="submit" value="Submit"> <input type="reset"> </font></td> </tr> <tr> <td colspan="2"> <table width="100%" border="0" cellpadding="4"> <tr> <th><a href="javascript:usePattern('/^[a-zA-Z0-9_\\-\\.function usePattern(PATTERN) { document.$TextToSearch)) echo '<font color="green">Match</font>'. sans-serif"> <input type="text" name="TextToSearch" value="<?= $TextToSearch ?>" size="50" maxlength="50"> </font></td> </tr> <tr> <td align="right"><font size="+2" face="Arial.

but not "fd". Start and End ( ^ $ ) A caret (^) at the beginning of a regular expression indicates that the string being searched must start with this pattern.<th><a href="javascript:usePattern('/^\\(?[2-9][0-9]{2}\\)?[\\. "food" and "foood". we'll test some regular expression in our browser using our regular expression tester at RegExp/Demos/Tester.]?[0-9]{3} [\\. and {}. In this section. we will look at how those characters are specified. A dollar sign ($) at the end of a regular expression indicates that the string being searched must end with this pattern. but not "faod". • The pattern foo$ can be found in "curfoo". Number of Occurrences ( ? + * {} ) The following symbols affect the number of occurrences of the preceding character (see footnote): ?. *. • The pattern foo? can be found in "food" and "fod". but not in "food".]?[0-9]{4}$/'). • The pattern ^foo can be found in "food". As we go through this section. • The pattern fo+ can be found in "fod"." class="reg">Phone</a></th> </tr> </table> </td> </tr> </table> </form> <div id="display" style="font-size:18pt. . +. font-family:Courier New"><b>PATTERN:</b> <?= $Pattern ?></div> </body> </html> Regular Expression Syntax A regular expression is a pattern that specifies a list of characters.php. but not in "barfood". A plus sign (+) indicates that the preceding character should appear one or more times in the pattern. A questionmark (?) indicates that the preceding character should appear zero or one times in the pattern.

"fo@d" and "fo. digits. but not "fod" or "foooood". • The pattern fo\dd can be found in "fo1d". Common Characters ( .A asterisk (*) indicates that the preceding character should appear zero or more times in the pattern. • The pattern fo\wd can be found in "food". but not in "food".d".n2} ) indicate that the preceding character should appear between n1 and n2 times in the pattern.g. • The pattern fo. Backslash-W ( \W ) represents any character except a word character. newline. • The pattern fo{2. "fod" and "food". but not in "fo*d". Backslash-w ( \w ) represents any word character (letters.} ) indicate that the preceding character should appear at least n times in the pattern. . etc.}d can be found in "food" and "foooood".d can be found in "food"."foood" and "fooood". "fo_d" and "fo4d". Curly brackets with one parameter and an empty second paramenter ( {n. "fo9d". but not in "food" or "fodd". It is the equivalent of [0-9]. space. • The pattern fo*d can be found in "fd". but not "food" or "fooood". • The pattern fo{3}d can be found in "foood" . Curly brackets with two parameters ( {n1. Curly brackets with one parameter ( {n} ) indicate that the preceding character should appear exactly n times in the pattern. "fo4d" and "fo0d". ) represents any character except a newline. \d \D \w \W \s \S ) A period ( . and "fo*d". "foad".4}d can be found in "food". but not "fod". Backslash-D ( \D ) represents any character except a digit. tab. • The pattern fo{2. • The pattern fo\Dd can be found in "food" and "foad". Backslash-d ( \d ) represents any digit.). • The pattern fo\Wd can be found in "fo*d". and the underscore (_) ). Backslash-s ( \s) represents any whitespace character (e. It is the equivalent of [^0-9]. but not in "fo4d".

but not in "fo d". • The pattern f(oo)?d can be found in "food" and "fd". but not in "fod". "faed" or "fd". the caret ( ^ ) is used for negation. Backslash-S ( \S ) represents any character except a whitespace character. The pattern f[aeiou]{2}d can be found in "faed" and "feod". • The pattern fo\. Subpatterns ( () ) Parentheses ( () ) are used to capture subpatterns. Grouping ( [] ) Square brackets ( [] ) are used to group options. but not in "food". Escape Character ( \ ) The backslash ( \ ) is used to escape special characters. • The pattern foo$|^bar can be found in "foo" and "bar". Form Validation Functions with Regular Expressions .d can be found in "fo. Negation ( ^ ) When used after the opening square bracket of a character class. but not in "fad" or "fed". This creates what is referred to as a "character class".d".• The pattern fo\sd can be found in "fo d". but not in "food" or "fo4d". but not "foobar". but not in "fod". • • The pattern f[aeiou]d can be found in "fad" and "fed". "fed" or "fd". but not in "food". "food" and "fo4d". Alternatives ( | ) The pipe ( | ) is used to create optional patterns. • The pattern f[^aeiou]d can be found in "fqd" and "f4d". • The pattern fo\Sd can be found in "fo*d".

Regular expressions can be used to write sophisticated form validation functions.')) { return false.'@')) { return false. } elseif (!strpos($Email. we wrote a checkEmail() function that looked like this: function checkEmail($Email) { $Email = trim($Email). } We can use a regular expression to make this function both simpler and more powerful: function checkEmail($Email) { $EmailPattern = '/^(\w+\.') < strpos($Email. } } So.$Email)). you make it easy to create a similar function library on the client side. For example. } elseif (!strpos($Email. earlier in the course.test(EMAIL)) { return true.'.'. . } 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+\.'@')) { return false.6)) { return false. } elseif (strrpos($Email. } return true. if (reEmail. return preg_match($EmailPattern. } else { return false.)+[A-Za-z]+$/. by using regular expressions in this way. if (!checkLength($Email.)*\w+@(\w+\.)+[A-Za-z]+$/'.

another user who sits down at the same computer several minutes later cannot continue with the first user's session. 2.gc_maxlifetime variable. The session length is also set in the php. The default value is 1440 seconds (24 minutes). an online investment site might have very short sessions. The amount of time varies depending on the web application. In the lesson on authenticaion. . The web server assigns the client a unique session id.. Continues current session if one exists. To write and read cookies. Most of the time. In this lesson. we created a login form and learned to authenticate users by comparing their emails and passwords to records in a database.. these unique ids are stored in session cookies that expire after the client hasn't interacted with the server for some amount of time.auto_start flag must be set to 1. Configuring Sessions In PHP. which the client uses to re-identify itself as it moves from page to page on the website. For example. Session Functions The following table shows the most common session functions. so that if a user leaves her computer without logging out. Sessions A session begins when a visiting client somehow identifies itself to the web server.Session Control and Cookies In this lesson of the PHP tutorial. session_unset Unsets all session variables. To have a user's session start as soon as the user visits the website. 1.ini file with the session. To maintain sessions to track user visits. we will use session variables to remember that the users are logged in as they go from page to page and we will use cookies to make it easier for users to log in on future visits. the session. Function session_start() Explanation Starts new session if one does not exist.ini file. () session_destr Kills session. you will learn. session management is configured in the php.

session_start(). show that session variable no longer //exists and then kill session.php <?php //Continue session. Code Sample: Sessions/Demos/Session1. ?> <hr/> <a href="Session2. Session variables are created in the $_SESSION array. echo $_SESSION['Greeting']. ?> Code Explanation The code above illustrates the following points.Function oy() Explanation Together. session_start(). echo $_SESSION['Greeting']. Session variables are deleted in the same way as other variables – using the unset() function. unset($_SESSION['Greeting']). ?> <a href="Session3.php <?php //Begin a session and create a session variable in //the $_SESSION array.php <?php //Continue session.php">Next page</a> Code Sample: Sessions/Demos/Session2. session_destroy(). the files below illustrate how sessions can be tracked. $_SESSION['Greeting'] = 'Hello world!'. • • • Pages that are part of the session should begin with a call to session_start(). echo $_SESSION['Greeting']. show that session variable still //exists and then unset the session variable session_start(). session_unset(). .php">Next page</a> Code Sample: Sessions/Demos/Session3.

Cookies Cookies are stored in text files that sit on the client machine. 1. There is no deletecookie() function. This should be called before calling session_destroy().'chocolate chip'. The cookie's expiration date (if this isn't set. If it does. You will also modify several other pages so that their content changes based on whether or not the user is logged in. o if (array_key_exists('EmployeeID'.• • All session variables can be unset with the session_unset() function. the cookie will expire when the browser window is closed). Cookies are set in the HTTP header. The domain name that can read the cookie. cookies are set with the setcookie() function. The directory path on the server that can read the cookie. you will create a login form that allows a user to log in to a site.'chocolate chip'. setcookie('flavor'. To delete a cookie. Open Sessions/Exercises/index. This file has been completed for you. o We've added an outer if condition to the body to check if EmployeeID already exists in the $_SESSION array. Note the following: o At the top of the document. Sessions are killed with a call to session_destroy(). In this exercise. In PHP. time()-10000). The cookie's value. rather than just a page on the site. The following code will set a cookie that expires in one week. A flag indicating whether the cookie should only be read over https. which can take several parameters including: • • • • • • The cookie's name (required). Exercise: Authentication with Session Control Duration: 30 to 40 minutes. setcookie('flavor'. time()+60*60*24*7). so they must be set before any HTML code is passed back to the browser. we start a session with session_start().$_SESSION)) . this means the user has already logged in. Web pages with the right permissions can read from and write to cookies. like this. set the expiration date to sometime in the past.php in your editor. They are generally used to track user information between visits.

she is remembered for the duration of her visit...php in your editor.php'. $_SESSION['FirstName'] .o o o o o o o o o o o o o o o o o o o o o o { echo '<div align="center"> Logged in as ' . Open Sessions/Exercises/Includes/Login.php. You may also find it useful to create a new include file (e. Add code to log the user out (i. $_SESSION['LastName'] .php. 4. ' ' . To send emails using PHP's built-in mail() function.php if you prefer) in your editor. Modify the code. } if (strlen($msg) > 0) { echo "<div align='center'>$msg</div>".php if the user is not logged in. You will need to modify index.php has been changed to include a "Log out" link. Open Sessions/Exercises/Logout.php. 2. Includes/LoginForm. Write code so that the user can indicate that she would like to be remembered between visits. . Open Sessions/Exercises/Includes/LoginCheck. Modify this script so that it only redirects to index.php. she should not have to log in again for a week. You will see that it currently contains code to redirect the page to index. Notice that it includes Includes/LoginCheck. Includes/Login. 5. 3.php) to hold the code that checks for the cookie Sending Email with PHP In this lesson of the PHP tutorial.e. '</div>'. a PHP extension with more features than mail(). CookieCheck. which points to Sessions/Exercises/Logout.$_POST)) { require 'Includes/Login.php. To send email using PHPMailer. 1. you will learn.php in your editor. If she chooses to be remembered. so that when the user logs in.g. delete all session variables and kill the session). Sessions/Exercises/Includes/Footer. last name and employee id. } if (!array_key_exists('LoggingIn'. } else { if (array_key_exists('LoggingIn'.php.php and Includes/Logout.$_POST)) { require 'Includes/LoginForm. } } 2.php (you can use LoginPear.php in your editor. Open Sessions/Exercises/OtherPage.php'. You should remember her first name.

if(mail($To. $Subject = $_POST['Subject'].php"> <input type="hidden" name="Submitted" value="true"/> Mail Server: <input type="text" name="Host" size="25"/><br/> To: <input type="text" name="To" size="25"/><br/> From: <input type="text" name="From" size="25"/><br/> Subject: <input type="text" name="Subject" size="25"/><br/> <textarea name="Message" cols="50" rows="10"></textarea><br/> <input type="submit" value="Send Email"/> </form> <?php } else { ini_set('SMTP'.mail() PHP has a built-in mail() function that makes it easy to send email. Additional headers (e. $To = $_POST['To']. $_POST['From']. Any additional parameters you may want to send to your mail server.g.$Message.$_POST)) { ?> <form method="post" action="Mail.$Subject. Reply-To) Optional. The email's subject.$From)) { . From. Code Sample: Email/Demos/Mail. The body of the email. $From = 'From: ' . Optional. Mail Parameters Method To Subject Message Additional Headers Additional Parameters Description The address to send the email to.$_POST['Host']). $Message = $_POST['Message'].php <html> <head> <title>Mail()</title> </head> <body> <?php if (!array_key_exists('Submitted'.

which is used to temporarily change configuration settings.ini file with the SMTP setting. Difficult to add attachments. Shortcomings of mail() The mail() function has many limitations. Difficult to send HTML-formatted emails. Note that the mail server is set with the ini_set() function. there are extensions that do provide these features. The following tables show some of the more common methods and properties of PHPMailer. he'll be presented with a form. you will need to have a mail server set up on your server. PHPMailer A very good email extension is PHPMailer. which is available for free at http://phpmailer. We will use PHPMailer in our examples and exercises. When the user fills out and submits that form. nt() AddBCC() Adds a "bcc" address. } else { echo "Message Not Sent". You can set the default mail server in the php. the mail() function will attempt to send an email to the address the user entered. The first time a visitor hits the page.net. • • • No support for SMTP authentication.sourceforge. Luckily. } } ?> </body> </html> Code Explanation For this example to work.echo "Message Sent". AddAttachme Adds an attachment from a path on the filesystem. Description . PHPMailer Methods Method AddAddress() Adds a "To" address.

Sets the Body of the message. . SMTPAut Sets SMTP authentication. PHPMailer Properties Propert y AltBody Body Description Sets the text-only body of the message. All hosts must be separated by semicolons. Utilizes the Username and Password h properties. e WordWra Sets word wrapping on the body of the message to a given p number of characters.PHPMailer Methods Method Description AddCC() Adds a "cc" address. Creates message and assigns Mailer. From Sets the From email address for the message. Usernam Sets SMTP username. Subject Sets the Subject of the message. IsHTML() IsSMTP() Send() Sets message type to HTML. This can be either an HTML or text body. Sets Mailer to send message using SMTP. AddReplyTo() Adds a "Reply-to" address. me Host Sets the SMTP hosts. If the message is not sent successfully then it returns false. FromNa Sets the From name of the message. Password Sets SMTP password. ErrorInfo Holds the most recent mailer error message.

php"). $Mail->IsSMTP(). $From = $_POST['From']. $FromName = $_POST['FromName']. $Mail->Username=$_POST['Username']. $Message = $_POST['Message'].php"> <input type="hidden" name="Submitted" value="true"/><br/> Mail Server: <input type="text" name="Host" size="25"/><br/> If authentication is required:<br/> Username: <input type="text" name="Username" size="25"/><br/> Password: <input type="password" name="Password" size="10"/> <hr/> To: <input type="text" name="To" size="25"/><br/> From Email: <input type="text" name="From" size="25"/><br/> From Name: <input type="text" name="FromName" size="25"/><br/> Subject: <input type="text" name="Subject" size="25"/><br/> <textarea name="Message" cols="50" rows="10"></textarea><br/> Using HTML: <input type="checkbox" name="HTML"/> <input type="submit" value="Send Email"/> </form> <?php } else { require("class.$_POST)) { $HTML = true. if (array_key_exists('HTML'. } else { $HTML = false.phpmailer.$_POST)) { ?> <form method="post" action="PHPMailer.$_POST)) { $Mail->SMTPAuth=true. // send via SMTP $Mail->Host = $Host. $Subject = $_POST['Subject'].Code Sample: Email/Demos/PHPMailer. $To = $_POST['To']. $Host = $_POST['Host']. //SMTP server if (array_key_exists('Username'.php <html> <head> <title>PHPMailer</title> </head> <body> <?php if (!array_key_exists('Submitted'. $Mail->Password=$_POST['Password']. } $Mail = new PHPMailer(). .

} else { $Mail->SMTPAuth=false. 4. which you'll need to get from the Northwind database. BCC yourself on the email. 2. 1. } else { echo "Message Not Sent<br/>". In the else block of the if condition add code that sends the user her password. $Mail->FromName = $FromName. This page contains a simple form that submits to the same page. $Mail->AddAddress($To). Test your solution in your browser. // set word wrap $Mail->IsHTML($HTML). } } ?> </body> </html> Code Explanation As you can see. $Mail->AddReplyTo($From). $Mail->Body = $Message. . You'll need this to check to see that your solution is working. $Mail->WordWrap = 50. Open Mail/Exercises/PasswordReminder. PHPMailer comes with a full set of intuitive methods and properties that make sending emails very easy. Otherwise. Exercise: Sending a Password by Email Duration: 20 to 30 minutes. $Mail->ErrorInfo. output the error to the browser. If the email fails to send. 5. echo "Mailer Error: " . 3. let the user know the password has been sent. 6. In this exercise. you will create a Password Reminder page that allows users to have their passwords sent to them by email. } $Mail->From = $From. $Mail->Subject = $Subject. if($Mail->Send()) { echo "Message Sent".php in your editor.

it will be necessary to store data in or access data from files. creates new file if one doesn't exist create and open for writing and reading (new in PHP 4. 4. access and work with directories on the server. 2. file_mode) path_to_file can either be a relative or an absolute path. Opening a File fopen() Syntax fopen (path_to_file..3. 5. you will learn.File System Management In this lesson of the PHP tutorial.2). get information about files on the server. However. 3. upload files to the server..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 open for appending and writing. File Modes File Mode r w a x r+ w+ a+ x+ open for reading open for writing (erases existing content). To To To To To read from files on the server. 1. fails and returns false if file already exists Description . in some cases.3. Most Web applications use databases to store large amounts of data. creates new file if one doesn't exist open for appending to end of content. write to files on the server. creates new file if one doesn't exist create and open for writing (new in PHP 4.

com Robert King Sales Representative rking@northwind.'a'). Reading from a File Opening a file for reading involves three steps: 1.com Margaret Peacock Sales Representative mpeacock@northwind.com Janet Leverling Sales Representative jleverling@northwind. but the file cannot be opened. it will continue reading until it reaches the end of the line. If the second argument is not included. Examine the file shown below. Close the file.com Code Explanation . Use conditional processing as shown below to handle this situation. fgets() fgets() is used to read a file one line at a time. 3. It will continue reading the line until the length .com Laura Callahan Inside Sales Coordinator lcallahan@northwind.com Andrew Fuller Vice President. Code Sample: Files/Demos/Employees.com Steven Buchanan Sales Manager sbuchanan@northwind.com Anne Dodsworth Sales Representative adodsworth@northwind.txt Nancy Davolio Sales Representative ndavolio@northwind.File Permissions Files that do no have the appropriate permissions settings will fail to open. Sales afuller@northwind.com Michael Suyama Sales Representative msuyama@northwind. Any errors can then be handled more gracefully. Open the file. 2. $MyFile = @fopen('MyFile.</b>'. Read the file.txt'. In this case. It requires one argument: the resource or "handle" for the file and accepts a second argument: the length of the line.1 have been read or it reaches the end of the line or the end of the file. if (!$MyFile) { echo '<b>Sorry. } else { // code for processing file } The @ symbol in front of first line of code is used to suppress errors. the fopen() function will return false and a warning will be given.

Employees. } ?> </body> </html> Other options for reading from files Functi on Description fgetss() Like fgets() but it strips out HTML and PHP tags. sends its contents to the browser. and closes the file. The code below opens Employees.txt". 999). reads and displays each line. echo $Employee. 'r'). if (!$MyFile) { echo '<p>Cannot open file. .txt is a tab-delimited text file. and closes the file. splits it into an array on newline characters. } fclose($MyFile). 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). () file() Opens a file. and closes the file. } else { while (!feof($MyFile)) { $Employee = fgets($MyFile.txt.'<br />'. fgetcsv Like fgets() but it splits the file on a specified delimiter rather than a () newline character. readfile Opens a file. Code Sample: Files/Demos/Employees.php <html> <head> <title>Employees</title> </head> <body> <h1>Employees</h1> <?php $MyFile = @fopen("Employees.'.

2. 3. $MyFile = @fopen('Employees. $OutputString='text to write'. If it did open. Close the file.Writing to a File Opening a file for writing involves three steps: 1. which is in the same directory. 3. Write to the file. Where is the solution? File Locking flock() (see footnote) flock() is used to lock a file so that two or more people do not get access to it at the same time. 1. 'a'). In this exercise you will write code to append entries to the Employees.output_string) The output_string is the text to write to the file. Exercise: Writing to a File Duration: 10 to 15 minutes. write the output string to the file and close the file. fwrite($MyFile.txt. 2. $OutputString). Open the file. See the following example of writing to a file. Create short versions of the form variables. Open Employees.txt. flock() takes two arguments: a file handler and a lock type. Open Files/Exercises/AddEmployee.php in your editor. Be sure to suppress errors. This helps protect the file from being corrupted. Write a condition that checks to see if the file failed to open. 2.txt'. . 3. The steps involved are: 1. fwrite() Syntax fwrite(file_pointer.txt for appending. Write code to save the entry in Employees. fclose($MyFile).

The file cannot be opened by others. fwrite($MyFile. X LOCK_U Unlocks file.Code Omitted ---- Uploading Files via an HTML Form (see footnote) In order to upload files via an HTML form.Code Omitted ---flock($MyFile. H LOCK_E Exclusive lock. Others can read file. LOCK_EX). flock() waits to get a lock. Syntax <form method="post" enctype="multipart/form-data"> The following example demonstrates how to safely allow the user to upload a file to the server.Lock Type Explanation LOCK_S Reading lock. flock($MyFile.$OutputString). N LOCK_N If a file is already locked by another user. B LOCK_NB tells it not to wait. Code Sample: Files/Demos/FileUpload.txt from being corrupted. fclose($MyFile). ---. the form tag's method must be set to "post" and the enctype must be set to "multipart/form-data" as shown below. Code Sample: Files/Demos/Locking.php ---. The code below shows how we should change Files/Solutions/AddEntry.php <html> <head> <title>Resume Upload</title> </head> <body style="text-align:center"> <?php .php to protect Employees. LOCK_UN).

EndPage(). $_POST['LastName'] . } } else { //This case happens if somehow the file . $FileType = $_FILES['Resume']['type']. $ResumeName. $ResumeName=$_POST['FirstName'] .$FileSavePath)) { echo 'Could not save file. } elseif ($FileType != 'text/plain') { echo "You have attempted to upload a file of type: $FileType.'.if (!array_key_exists('Submitted'.txt'. '_Resume. EndPage().$_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']. EndPage(). if ($FileError) { echo "We could not upload the file:<br/>$FileError". } $FileSavePath = 'Resumes/' .". <br/>Only text files allowed. '_' . $FileSize = $_FILES['Resume']['size']. $FileError = $_FILES['Resume']['error']. if (is_uploaded_file($ResumeFile)) { if (!move_uploaded_file($ResumeFile.

} function makeFileSafe($FilePath) { $FP = @fopen($FilePath. 2. it displays an appropriate message and calls the EndPage() user function. If it finds any. return $Contents. it will attempt to upload and save the user's resume. The next piece of code attempts to upload the file: . 3. the script assigns values to short named variables. The form also has an input field of type file that is used to browse for the file to upload. } ?> </body> </html> //we are working with was already on the server. echo 'Hey. rewind($FP). The first time it is loaded.} $Resume=makeFileSafe($FileSavePath). $Contents = strip_tags($Contents). which just closes the HTML page. //It's to stop hackers. The next block of code is the if-elseif-elseif statement.$Contents). fwrite($FP. ?> <h2>Thanks!</h2> <b>We got your resume. which checks for errors.'r+'). } $Contents = fread($FP. what is going on here? Are you being bad?'. When the form is submitted. Code Explanation The first thing to notice about this page is that it submits to itself. 4.filesize($FilePath)). if (!$FP) { return "Could not read file". When the form is submitted. exit. fclose($FP). 1. it will show the form.</b><hr> <form> <textarea cols="60" rows="20"><?echo $Resume?></textarea> </form> </p> <?php } function EndPage() { echo '</body></html>'. EndPage().

5. if (is_uploaded_file($ResumeFile)) 6. { 7. if (!move_uploaded_file($ResumeFile,$FileSavePath)) 8. { 9. echo 'Could not save file.'; 10. EndPage(); 11. } 12. } 13. else 14. { 15. //This case happens if somehow the file 16. //we are working with was already on the server. 17. //It's to stop hackers. 18. echo 'Hey, what is going on here? 19. Are you being bad?'; 20. EndPage(); }

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.

Getting File Information
The following code sample illustrates how to get information about a file using PHP.

Code Sample: Files/Demos/FileInfo.php
<html> <head> <title>File Details</title> </head> <body> <?php $CurrentDir = 'Resumes/'; $File = basename('J_C_Resume.txt'); echo '<h1>Details of file: ' . $File.'</h1>'; $File = $CurrentDir.$File; echo '<h2>File data</h2>'; echo 'File last accessed: ' . date('j F Y H:i', fileatime($File)) . '<br/>'; echo 'File last modified: ' . date('j F Y H:i', filemtime($File)).'<br/>'; echo 'File type: ' . filetype($File).'<br/>'; echo 'File size: '.filesize($File).' bytes<br/>'; echo '<h2>File tests</h2>'; echo 'is_dir: ' . (is_dir($File)? 'true' : 'false') . '<br/>'; echo 'is_file: ' . (is_file($File)? 'true' : 'false').'<br/>'; 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() filesize() is_dir() is_file() Returns the type of file (e.g, file or dir). Returns the size of the file in bytes. Returns true if the passed value is a directory, false if it isn't. Returns true if the passed value is a file, false if it isn't.

is_readabl Returns true if the file is readable, false if it isn't. e() is_writable Returns true if the file is writable, false if it isn't. ()

More File Functions
A few more file functions are shown below:
Function Description

file_exists(path_to_ Checks to see if a file exists. file) filesize(path_to_file Returns the size of file in bytes. ) unlink(path_to_file) Deletes the file.

Function

Description

copy()

Copies a file. Takes two arguments: the path to the source file and the destination to copy the source file to. Moves a file. Takes two arguments: the path to the source file and the destination to move the source file to. If the path and destination are the same with the exception of the filename, rename() simply renames the file.

rename()

Directory Functions
The following table shows some of the more common directory functions.
Functi on Description

mkdir() Creates a directory. rmdir() Deletes a directory. opendir Opens a directory for reading. () readdir( Reads the contents of an open ) directory.

Getting a Directory Listing
To get a directory listing, use the opendir() function to open the directory and the readdir() function to read its contents. Then loop through its contents with a while loop outputting the name of each file and folder.

Exercise: Creating a Resume Management Page
Duration: 20 to 30 minutes.

In this exercise, you will create a simple resume management page that will list all the resumes currently in the resumes folder and allow you to remove resumes from the folder.
1. Open Files/Exercises/FileListing.php in your editor. Much of the file is done already. 2. Complete the fileDetails() function so that it will properly display the details of the passed file.

we have stored those files in a directory under the web root. Write a renameFile() function and add a form to the fileDetails() function that allows the user to provide a new name for the file. when it is important to be able to access and change data quickly and to maintain the integrity of that data. Write the deleteFile() function. In this lesson. Modify this link so that it passes the file path in the "Delete" variable via the query string. Where is the solution? File System Management Conclusion Although writing to and reading from files can be useful in certain situations. 4. Write the browseDir() function. you should store any uploaded files above or outside of the web root. it is often better to use a database. At the end of the if block of the fileDetails() function there is a "Delete File" link.3. For security reasons. 5. Many websites allow visitors to upload files via a form. . In practice. this is generally not a good idea.