100% found this document useful (1 vote)
500 views

PHP Basic

This document provides an overview of PHP basics, including: - PHP allows embedding server-side code into HTML pages, which is executed on the server and outputs dynamic web pages. - It introduces basic PHP syntax like tags and variables, and built-in functions like echo. - The document explains PHP variables, data types, and variable scope, as well as common PHP operators and functions for manipulating variables. - The goal is to teach readers how to write their first simple PHP script after learning PHP's basic building blocks and syntax.

Uploaded by

Rajiv Sivalingam
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
100% found this document useful (1 vote)
500 views

PHP Basic

This document provides an overview of PHP basics, including: - PHP allows embedding server-side code into HTML pages, which is executed on the server and outputs dynamic web pages. - It introduces basic PHP syntax like tags and variables, and built-in functions like echo. - The document explains PHP variables, data types, and variable scope, as well as common PHP operators and functions for manipulating variables. - The goal is to teach readers how to write their first simple PHP script after learning PHP's basic building blocks and syntax.

Uploaded by

Rajiv Sivalingam
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 123

http://www.learnphp-tutorial.com/php-basics.

cfm
PHP Tutorial
PHP Basics
In this lesson, we will introduce you to PHP and show you how it works. You will also be
able to write your first PHP script after learning the basic syntax of PHP.
Lesson Goals
Learn what PHP is.
Learn how PHP works.
Write a simple PHP page.
Understand and work with simple PHP variables.
Use PHP operators.
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">
PHP CODE GOES
IN HERE
</script>

HTML or Script style tags.
<?
PHP CODE GOES
HERE
?>

"Short" tags. Must be enabled via the short_open_tag php.ini configuration
file directive.
<%
PHP CODE GOES
HERE
%>

ASP-style tags. Must be enabled via the asp_tags php.ini configuration file
directive.
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
1
2
3
4
5
6
7
// 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
1 function_name(arguments);
The example below shows how the phpinfo() function works.
Code Sample:
PhpBasics/Demos/PhpInfo.php
1
2
3
4
5
6
7
8
9
10
11
12
13
<!DOCTYPE HTML>
<html>
<head>
<meta charset="UTF-8">
<title>PHPINFO</title>
</head>
<body>
<?php
//Output information on the PHP environment
phpinfo();
?>
</body>
</html>
Introduction to php.net
PHP functions are well documented at http://www.php.net. You can quickly look up
documentation on a function by going to http://www.php.net/function_name. For example, to
see documentation on phpinfo(), go to http://www.php.net/phpinfo.
Another very good function reference is located at http://www.phpdig.net/ref.
Hello World!
It is an unwritten rule that every programming course must contain a "Hello World!" script.
Here it is:
Code Sample:
PhpBasics/Demos/HelloWorld.php
1 <!DOCTYPE HTML>
2
3
4
5
6
7
8
9
10
11
12
13
<html>
<head>
<meta charset="UTF-8">
<title>Hello World!</title>
</head>
<body>
<?php
//Write out Hello World!
echo 'Hello World!';
?>
</body>
</html>
Notice the following about the above code:
Code between <?php and ?> is processed by the PHP interpreter.
The echo command is used to print text back to the browser.
This code isn't very exciting. In fact, PHP doesn't buy us anything here as we could have just
as easily output the result using straight HTML. There is nothing dynamic about this script.
After learning about variables, we'll take a look at some more interesting examples.
Variables
PHP variables begin with a dollar sign ($) as shown below.
Syntax
$varName = "Value";
Variable Types
Variable Type Explanation
Integer whole number
Variable Type Explanation
Double real number
String string of characters
Boolean true or false
Array list of items
Object instance of a class
Variable Names (Identifiers)
Variable, function and class names are all identifiers and all follow the rules above, with the
exception that function names are not case sensitive.
consist of letters, digits, underscores and dollar signs
cannot begin with a digit
are case sensitive
Type Strength
PHP is weakly typed, meaning that variables do not need to be assigned a type (e.g, Integer)
at the time they are declared. Rather, the type of a PHP variable is determined by the value
the variable holds and the way in which it is used.
Hello Variables!
Here is the "Hello World!" script again, but this time we use a variable.
Code Sample:
PhpBasics/Demos/HelloVariables.php
1
2
3
4
5
6
<?php
$greeting = 'Hello World!';
?>
<!DOCTYPE HTML>
<html>
<head>
<meta charset="UTF-8">
7
8
9
10
11
12
13
14
15
<title><?php echo $greeting; ?></title>
</head>
<body>
<?php
echo $greeting;
?>
</body>
</html>
This time the string "Hello World!" is stored in the $greeting variable, which is output in
the title and body of the page with an echo command.
Variable Scope
A variable's scope determines the locations from which the variable can be accessed. PHP
variables are either superglobal, global, or local.
Variable
Scope
Explanation
superglobal
Superglobal variables are predefined arrays, including $_POST and $_GET. They are
accessible from anywhere on the page.
global
Global variables are visible throughout the script in which they are declared. However,
they are not visible within functions in the script unless they are re-declared within the
function as global variables.
function
Variables in the function scope are called local variables. Local variables are local to the
function in which they are declared.
Superglobals
Again, superglobal variables are predefined arrays, including $_POST and $_GET and are
accessible from anywhere on the page. The complete list of superglobals is shown below.
$_GET - variables passed into a page on the query string.
$_POST - variables passed into a page through a form using the post method.
$_SERVER - server environment variables (e.g, $_SERVER['HTTP_REFERER'] returns the
URL of the referring page).
$_COOKIE - cookie variables.
$_FILES - variables containing information about uploaded files.
$_ENV - PHP environment variables (e.g, $_ENV['HTTP_HOST'] returns the name of the
host server.
Which environment variables are available depends on the specific server setup and
configuration.
$_REQUEST - variables passed into a page through forms, the query string and cookies.
$_SESSION - session variables.
The elements within superglobal variables can be accessed in three different ways, which the
authors of PHP and MySQL Web Development refer to as short style, medium style, and long
style.
PHP & MySQL Web Develpoment, Third Edition.
Style Syntax (using $_GET) Notes
Short $varname
Convenient, but it makes it difficult to distinguish
superglobal variables from other variables in the
code.
Requires register_globals config setting to
be on.
Medium $_GET['varname']
Recommended approach.
Happy medium between convenience and clarity.
Not available before v. 4.1.
Long $HTTP_GET_VARS['varname']
Inconvenient to type.
Deprecated, but still supported in current
versions.
Can be disabled via the register_long_arrays
directive in the php.ini file.
Many of these superglobals will be covered later in the course.
Constants
Constants are like variables except that, once assigned a value, they cannot be changed.
Constants are created using the define() function and by convention (but not by rule) are in
all uppercase letters. Constants can be accessed from anywhere on the page.
Syntax
define('CONST_NAME',VALUE);
Variable-Testing and Manipulation Functions
For a complete list of variable functions see http://www.php.net/manual/en/ref.var.php.
PHP provides built-in functions for checking if a variable exists, checking if a variable holds
a value, and removing a variable.
To output the results of these functions to a browser, use the var_dump() function (e.g.
var_dump(isset($a));).
Function Explanation Example
isset() Checks to see if a variable exists. Returns true or false. isset($a)
unset() Removes a variable from memory. unset($a)
empty() Checks to see if a variable contains a non-empty, non-false value. empty($a)
PHP Operators
Operators in PHP are similar to those found in many modern C-like programming languages.
Mathematical Operators
Operator Name Example
+ Addition $a + $b
- Subtraction $a - $b
* Multiplication $a * $b
/ Division $a / $b
% Modulus $a % $b
String Operators
Operator Name Example
. Concatenation
$a . $b
'Hello' . ' world!'

Assignment Operators
Operator Name Example
= Assignment
$a = 1;
$c = 'Hello' . ' world!';

+=
-=
*=
/=
%=
.=

Combination Assignment
$a += 1;
$a -= 1;
$a *= 2;
$a /= 2;
$a %= 2;
$a .= ' world!';

++ Increment By One
$a++;
++$a;

-- Decrement By One
$a--;
--$a;

Other Operators
Operator Name Example
?: Ternary $foo = ($age >= 18) ? 'adult' : 'child';
@ Error Suppression $a = @(1/0);
Creating Dynamic Pages
Single Quotes vs. Double Quotes
In PHP, for simple strings you can use single quotes and double quotes interchangeably.
However, 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
Escape sequences are used for characters that cannot easily be output within strings. Common
escape sequences are \n for a newline, \t for a tab, \\ for a backslash, \" for a double quote,
and \$ for a dollar sign.
Compare the examples below.
Code Sample:
PhpBasics/Demos/SingleQuotes.php
1
2
3
4
5
6
7
8
9
10
11
12
13
<!DOCTYPE HTML>
<html>
<head>
<meta charset="UTF-8">
<title>Single Quotes</title>
</head>
<body>
<?php
$person = 'George';
echo '\tHello\n$person!!';
?>
</body>
</html>
Because of the use of single quotes above, the string "\tHello\n$person!!" will be output
literally, as shown below.

Code Sample:
PhpBasics/Demos/DoubleQuotes.php
1
2
3
4
5
6
7
8
9
10
11
12
13
<!DOCTYPE HTML>
<html>
<head>
<meta charset="UTF-8">
<title>Single Quotes</title>
</head>
<body>
<?php
$person = "George";
echo "\tHello\n$person!!";
?>
</body>
</html>
This time, because of the double quotes, the string will be parsed for variables and special
characters and will be output as shown below.

To see the effect of the special characters (\n and \t), you will have to view the source of the
resulting page.
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
1 http://www.webucator.com/hello.php?greet=Hello&who=World
The part of the URL that follows the question mark is called the query string. One or more
name-value pairs can be passed to the server in this way. Each name-value pair is separated
by an ampersand (&). The processing page can read these name-value pairs and use them to
determine its response.
The HTML page below shows an example of how these name-value pairs might be passed.
Code Sample:
PhpBasics/Demos/HelloHi.html
1
2
3
4
5
6
7
8
9
10
11
12
13
<!DOCTYPE HTML>
<html>
<head>
<meta charset="UTF-8">
<title>Preferred Greeting</title>
</head>
<body>
Do you prefer a formal greeting or an informal greeting?
<ul>
<li><a href="HelloHi.php?greet=Hello">Formal</a></li>
<li><a href="HelloHi.php?greet=Hi">Informal</a></li>
<li><a href="HelloHi.php?greet=Howdy">Friendly</a></li>
</ul>
</body>
</html>
14
15
Code Sample:
PhpBasics/Demos/HelloHi.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
<?php
//Assign the passed variable to a variable with
//a more convenient name.
$greeting = $_GET['greet'];
?>
<!DOCTYPE HTML>
<html>
<head>
<meta charset="UTF-8">
<title><?= $greeting ?> World!</title>
</head>
<body>
<?php
echo "$greeting World!";
?>
</body>
</html>
Notice the following about the code above.
Variable names begin with a dollar sign ($).
Values passed in the query string are part of the $_GET array and can be accessed using the
following syntax: $_GET['fieldname'].
A shortcut for echo 'text to print'; is <?= 'text to print' ?>.
Many PHP developers feel that it is best practice to avoid using this shortcut syntax
for echo. One reason for this is that the shortcut syntax makes the resulting PHP file
impossible to parse as XML. Another is that the short_open_tag directive must be
turned on for it to work. See http://us3.php.net/manual/en/ini.core.php#ini.short-open-
tag
PHP Tutorial
Flow Control
In this lesson you will learn about flow control in PHP with if-elseif-else conditions and with
loops.
Lesson Goals
Work with if-elseif-else conditions in PHP.
Work with switch/case statements in PHP.
Work with loops in PHP.
Conditional Processing
Conditional processing allows programmers to output different code based on specific
conditions. There are two conditional structures in PHP - if-elseif-else and switch/case.
If Conditions
Simple if statement
Syntax
if (conditions)
Do this;
In the above code, the Do this; statement will either run or not run depending on whether or
not the conditions are true. This syntax can only be used when the condition affects a single
line of code. For a block of code, use the following syntax.
Syntax
if (conditions)
{
Do this;
Then do this;
And this too;
}
The lines of code affected by the if condition are put in a code block, which is surrounded by
curly brackets to indicate that all of the code either should or should not be executed,
depending on the result of the if condition.
if-else statement
Syntax
if (conditions)
{
Do this;
}
else
{
Do that;
}
if-elseif-else statement
Syntax
if (conditions)
{
Do this;
}
elseif (other conditions)
{
Do that;
}
else
{
Do this other thing;
}
The two syntax blocks above show an if-else and an if-elseif-else statement, which can
have any number of elseif blocks.
The following table shows PHP's comparison operators.
Comparison Operators
Operator Description
==
Equals
!=
Doesn't equal
>
Is greater than
<
Is less than
>=
Is greater than or equal to
<= Is less than or equal to
=== Identical (same value and same type)
!== Not Identical
The following example demonstrates an if-elseif-else statement.
Code Sample:
FlowControl/Demos/If.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
<!DOCTYPE HTML>
<html>
<head>
<meta charset="UTF-8">
<title>if-elseif-else</title>
</head>
<body>
<?php
$age = 21;
if ($age >= 21)
{
echo 'You can vote and drink!';
}
elseif ($age >= 18)
{
echo 'You can vote, but can\'t drink.';
}
else
{
echo 'You cannot vote or drink.';
}
?>
</body>
</html>
The file is relatively simple. You can see the different results by changing the value of $age.
Compound If Statements
More complex if statements often require that several conditions be checked. The table below
shows and and or operators for checking multiple conditions and the not operator for
negating a boolean value (i.e, turning true to false or vice versa).
Logical Operators
Operator Name Example
&&
AND
$a && $b
||
OR
$a || $b
!
NOT
!$b
The following example shows these logical operators in practice.
Code Sample:
FlowControl/Demos/If2.php
1
2
3
<!DOCTYPE HTML>
<html>
<head>
<meta charset="UTF-8">
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
<title>if-elseif-else</title>
</head>
<body>
<?php
$age = 21;
$citizen = false;
if ($age >= 21 && !$citizen)
{
echo 'You can drink, but can\'t vote.';
}
elseif ($age >= 21)
{
echo 'You can vote and drink!';
}
elseif ($age >= 18 && $citizen)
{
echo 'You can vote, but can\'t drink.';
}
else
{
echo 'You cannot vote or drink.';
}
?>
</body>
</html>
switch/case
A switch/case statement is similar to an if statement, except that it can only check for an
equality comparison of a single expression. It cannot, for example, be used to check if one
value is higher than another.
Syntax
1
2
3
4
5
6
7
8
9
10
11
12
13
14
switch (expression)
{
case 'a' :
echo 'expression is a';
break;
case 'b' :
echo 'expression is b';
break;
case 'c' :
echo 'expression is c';
break;
default :
echo 'expression is unknown';
break;
}
15
The break statement is important. Without it, after a single match is found, all following
statements will execute.
The following example demonstrates a switch/case statement without break statements.
Code Sample:
FlowControl/Demos/Switch.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
<!DOCTYPE HTML>
<html>
<head>
<meta charset="UTF-8">
<title>switch/case</title>
</head>
<body>
<?php
$quantity = 1;
switch ($quantity)
{
case 1 :
echo 'Quantity is 1';
case 2 :
echo 'Quantity is 2';
default :
echo 'Quantity is not 1 or 2';
}
?>
</body>
</html>
The screenshot below shows the result.

Notice that, once a match is found, all remaining echo statements are output. The following
example shows how this can be fixed by adding break statements.
Code Sample:
FlowControl/Demos/SwitchWithBreak.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
<!DOCTYPE HTML>
<html>
<head>
<meta charset="UTF-8">
<title>switch/case</title>
</head>
<body>
<?php
$quantity = 1;
switch ($quantity)
{
case 1 :
echo 'Quantity is 1';
break;
case 2 :
echo 'Quantity is 2';
break;
default :
echo 'Quantity is not 1 or 2';
}
?>
</body>
</html>
This time, only the first statement is output:

Loops
As the name implies, loops are used to loop (or iterate) over code blocks. The following
section shows the syntax for different types of loops. Each loop will return "12345".
There are several types of loops in PHP.
while
do...while
for
foreach
foreach loops will be covered in the Arrays lesson.
while
while loops are used to execute a block of code repeatedly while one or more conditions is
true.
Syntax
1
2
3
4
5
6
$a=1;
while ($a < 6)
{
echo $a;
$a++;
}
do...while
do...while loops are used to execute a block of code repeatedly until one or more
conditions is found to be false. The difference between while loops and do...while loops is
that the condition is checked after the code block is executed. This means that, in a
do...while loop, the code block will always be executed at least once.
Syntax
1
2
3
4
5
6
7
$a=1;
do
{
echo $a;
$a++;
}
while ($a < 6);
for
A for loop takes three expressions separated by semi-colons and grouped in parentheses
before the block to be iterated through.
1. The first expression is executed once before the loop starts. It is usually used to
initialize the conditions.
2. The second expression is evaluated before each iteration through the loop. If it
evaluates to false, the loop ends.
3. The third expression is executed at the end of each iteration through the loop. It is
usually used to make changes that can affect the second expression.
Syntax
1
2
3
4
for ($a=1; $a < 6; $a++)
{
echo $a;
}
break and continue
To break out of a loop, insert a break statement.
Syntax
1
2
3
4
5
6
7
8
for ($a=1; $a < 6; $a++)
{
echo $a;
if ($a > 3)
{
break;
}
}
To jump to the next iteration of a loop without executing the remaining statements in the
block, insert a continue statement.
Syntax
1
2
3
4
5
6
7
8
for ($a=1; $a < 6; $a++)
{
if ($a == 3)
{
continue;
}
echo $a;
}
PHP Tutorial
Arrays
Up to this point, we have dealt only with variables that store single values, called scalar
variables. In this lesson, we will be covering arrays. Arrays are variables that store sets of
values.
Lesson Goals
Work with indexed arrays.
Work with associative arrays.
Work with two-dimensional arrays.
Work with array-manipulation functions.
Indexed Arrays
Indexed arrays are similar to tables with a single column. An indexed array can contain zero
or more elements. In PHP, like in many programming languages, the first element of an array
is in the "zeroeth" position. An array with no elements has a zero length.
Initializing Arrays
Arrays are initialized with the array() function, which can take a list of comma-delimited
values that become the elements in the new array. The following lines of code initializes a
zero-length array and then adds four elements to the array.
Syntax
1
2
3
4
5
$beatles = array();
$beatles[0] = 'John';
$beatles[1] = 'Paul';
$beatles[2] = 'George';
$beatles[3] = 'Ringo';
The first line above is actually optional as the second line will create the array if one does not
already exist. However, it is a better coding practice to explicitly initialize the array. The
$beatles array could also be created in a single line as follows.
Syntax
1 $beatles = array('John','Paul','George','Ringo');
Appending to an Array
If you know how many elements are in an array, you can append to the array by specifying
the index. For example, you could append to the $beatles array shown above as follows:
Syntax
1 $beatles[5] = 'Nat';
However, sometimes you don't know how many elements are in an array. Although you can
easily figure this out, doing so requires an extra step. PHP provides an easy way of appending
to an array of any length. Simply leave out the index.
Syntax
1 $beatles[] = 'Nat';
Reading from Arrays
Reading from arrays is just a matter of pointing to a specific index or key.
Syntax
1 echo $beatles[2]; //outputs George to the browser
Looping through Arrays
The following code will loop through the entire $beatles array outputting each element to
the browser.
Syntax
1
2
3
4
foreach ($beatles as $beatle)
{
echo "$beatle<br>";
}
The above code snippets are combined in the following example.
Code Sample:
Arrays/Demos/IndexedArrays.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
<!DOCTYPE HTML>
<html>
<head>
<meta charset="UTF-8">
<title>Indexed Arrays</title>
</head>

<body>
<h1>Indexed Arrays</h1>
<?php
$beatles = array();
$beatles[0] = 'John';
$beatles[1] = 'Paul';
$beatles[2] = 'George';
$beatles[3] = 'Ringo';

echo $beatles[2]; //outputs George to the browser

$beatles[] = 'Nat';
?>
<hr>
<?php
foreach ($beatles as $beatle)
{
echo "$beatle<br>";
}
?>
</body>
</html>
28
29
Associative Arrays
Whereas indexed arrays are indexed numerically, associative arrays are indexed using names.
For example, instead of Ringo being indexed as 3, he could be indexed as "drummer".
Initializing Associative Arrays
Like with indexed arrays, we can intialize a zero-length associative array and then add
elements.
Syntax
1
2
3
4
5
$beatles = array();
$beatles['singer1'] = 'Paul';
$beatles['singer2'] = 'John';
$beatles['guitarist'] = 'George';
$beatles['drummer'] = 'Ringo';
Or the array could be created in a single line as follows.
Syntax
1
2
3
4
$beatles = array('singer1' => 'John',
'singer2' => 'Paul',
'guitarist' => 'George',
'drummer' => 'Ringo');
Reading from Associative Arrays
Reading from associative arrays is as simple as reading from indexed arrays.
Syntax
1 echo $beatles['drummer']; //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.
Syntax
1
2
3
4
foreach ($beatles as $key => $beatle)
{
echo "<b>$key:</b> $beatle<br>";
}
The above code snippets are combined in the following example.
Code Sample:
Arrays/Demos/AssociativeArrays.php
1
2
3
4
5
6
7
8
9
10
11
12
13
<!DOCTYPE HTML>
<html>
<head>
<meta charset="UTF-8">
<title>Associative Arrays</title>
</head>

<body>
<h1>Associative Arrays</h1>
<?php
$beatles = array('singer1' => 'John',
'singer2' => 'Paul',
'guitarist' => 'George',
'drummer' => 'Ringo');
14
15
16
17
18
19
20
21
22
23
24
25
26

echo $beatles['drummer']; //outputs Ringo to the browser
?>
<hr>
<?php
foreach ($beatles as $key => $beatle)
{
echo "<b>$key:</b> $beatle<br>";
}
?>
</body>
</html>
Superglobal Arrays
The superglobal arrays are associative arrays. The file below outputs all the contents of the
superglobal arrays using foreach loops.
Code Sample:
Arrays/Demos/SuperGlobals.php
1
2
3
4
5
6
7
8
<?php
session_start();
?>
<!DOCTYPE HTML>
<html>
<head>
<meta charset="UTF-8">
<title>Superglobal Arrays</title>
</head>
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35

<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>$_ENV</h2>
<ol>
<?php
foreach ($_ENV 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>";
}
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
?>
</ol>
<hr>
<h2>$_GET</h2>
<ol>
<?php
foreach ($_GET as $key => $item)
{
echo "<li><b>$key:</b> $item<br></li>";
}
?>
</ol>
<hr>
<h2>$_POST</h2>
<ol>
<?php
foreach ($_POST as $key => $item)
{
echo "<li><b>$key:</b> $item<br></li>";
}
?>
</ol>
<hr>
<h2>$_REQUEST</h2>
<ol>
<?php
foreach ($_REQUEST as $key => $item)
{
echo "<li><b>$key:</b> $item<br></li>";
}
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
?>
</ol>
<hr>
<h2>$_SESSION</h2>
<ol>
<?php
foreach ($_SESSION as $key => $item)
{
echo "<li><b>$key:</b> $item<br></li>";
}
?>
</ol>
<hr>
<h2>$_SERVER</h2>
<ol>
<?php
foreach ($_SERVER as $key => $item)
{
echo "<li><b>$key:</b> $item<br></li>";
}
?>
</ol>
</body>
</html>
90
91
92
93
Don't worry about the session_start() statement at the top. We'll cover that in detail later
in the course.
Two-dimensional Arrays
In PHP, two-dimensional arrays are arrays that contain arrays. You can think of the outer
array as containing the rows and the inner arrays as containing the data cells in those rows.
For example, a two-dimensional array called $rockBands could contain the names of the
bands and some of the songs that they sing. Below is a grid that represents such a two-
dimensional array.
rockBand Song1 Song2 Song3
Beatles Love Me Do Hey Jude Helter Skelter
Rolling Stones Waiting on a Friend Angie Yesterday's Papers
Eagles Life in the Fast Lane Hotel California Best of My Love
The following code creates this two-dimensional array. The internal arrays are highlighted.
Note that the header row is not included.
Syntax
1
2
3
4
5
6
7
$rockBands = array(
array('Beatles','Love Me Do', 'Hey Jude','Helter Skelter'),
array('Rolling Stones','Waiting on a Friend','Angie',
'Yesterday\'s Papers'),
array('Eagles','Life in the Fast Lane','Hotel California',
'Best of My Love')
)
Reading from Two-dimensional Arrays
To read an element from a two-dimensional array, you must first identify the index of the
"row" and then identify the index of the "column." For example, the song "Angie" is in row
1, column 2, so it is identified as $rockBands[1][2].
Remember that the first row is row 0 and the first column is column 0.
Looping through Two-dimensional Arrays
To loop through a two-dimensional array, you need to nest one loop inside of another. The
following code will create an HTML table from our two-dimensional array.
Syntax
1
2
3
4
5
6
7
8
9
10
11
12
13
<table border="1">
<?php
foreach($rockBands as $rockBand)
{
echo "<tr>";
foreach($rockBand as $item)
{
echo "<td>$item</td>";
}
echo "</tr>";
}
?>
</table>
The above code snippets are combined in the following example to output a rockBands table.
Code Sample:
Arrays/Demos/TwoDimensionalArrays.php
1 <!DOCTYPE HTML>
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
<html>
<head>
<meta charset="UTF-8">
<title>Two-dimensional Arrays</title>
</head>

<body>
<h1>Two-Dimensional Arrays</h1>
<?php
$rockBands = array(
array('Beatles','Love Me Do', 'Hey Jude','Helter Skelter'),
array('Rolling Stones','Waiting on a Friend','Angie','Yesterday\'s
Papers'),
array('Eagles','Life in the Fast Lane','Hotel California','Best of My
Love')
);
?>
<table border="1">
<tr>
<th>rockBand</th>
<th>Song 1</th>
<th>Song 2</th>
<th>Song 3</th>
</tr>
<?php
foreach($rockBands as $rockBand)
{
echo '<tr>';
foreach($rockBand as $item)
{
echo "<td>$item</td>";
29
30
31
32
33
34
35
36
37
}
echo '</tr>';
}
?>
</table>
</body>
</html>
Array Manipulation Functions
The following table shows some of the more common array manipulation functions.
For a complete list of array functions, see http://www.php.net/array
Useful Array Functions
Function Explanation
sort()
Sorts an array alphabetically. Elements will be assigned to new index
numbers.
asort()
Sorts associative arrays alphabetically by value. The index association
remains intact.
ksort()
Sorts associative arrays alphabetically by key. The index association remains
intact.
rsort()
Reverse sorts an array alphabetically. Elements will be assigned to new
index numbers.
arsort()
Reverse sorts associative arrays alphabetically by value. The index
association remains intact.
krsort()
Reverse sorts associative arrays alphabetically by key. The index association
remains intact.
shuffle()
Randomly sorts the array. For the order to be sorted differently each time,
Useful Array Functions
Function Explanation
the random number generator needs to be seeded with rsand().
array_reverse() Returns an array with the elements in reverse order.
array_walk() Applies a user function to every element of an array.
count() Returns the number of elements in an array.
explode() Converts a string to an array by splitting it on a specified separator.
is_array()
Takes one parameter and returns true or false depending on whether the
parameter passed is an array.
array_keys() Returns all the keys of an associative array as an array.
array_key_exists() Checks to see if a specified key exists in an array.
PHP Tutorial
PHP and HTML Forms
In this lesson, you will learn how to process form data in PHP.
Lesson Goals
Process form data with PHP.
HTML Forms
How HTML Forms Work
A very common way to pass data from one page to another is through HTML forms. There
are two methods of submitting data through a form: the get method and the post method. The
method used is determined by the value of the method attribute of the form tag. The default
method is get.
Get Method
When the get method is used, data is sent to the server in name-value pairs as part of the
query string. The get method is most commonly used by search pages and is useful when it is
important to be able to bookmark the resulting page (i.e, the page that is returned after the
form is submitted).
Post Method
When the post method is used, data is sent to the server in name-value pairs behind the
scenes. The two major advantages of the post method are:
The name-value pairs are not visible in the location bar, so sensitive data such as
passwords are not displayed on the screen.
Files, such as images and Office documents, can be uploaded via the form.
The major disadvantage is that the resulting page cannot be bookmarked.
A Sample HTML Form
The following is a sample HTML form for inserting an employee record into a database.
Code Sample:
Forms/Demos/AddEmployee.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
<!DOCTYPE HTML>
<html>
<head>
<meta charset="UTF-8">
<title>Add Employee</title>
</head>
<body>
<h1>Add Employee</h1>
<form method="post" action="ProcessEmployee.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.">Dr.
<input type="radio" name="TitleOfCourtesy" value="Mr.">Mr.
<input type="radio" name="TitleOfCourtesy" value="Mrs.">Mrs.
<input type="radio" name="TitleOfCourtesy" value="Ms.">Ms.
</td>
</tr>
<tr>
<td>Birth date:</td>
<td>
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
<select name="BirthMonth">
<option value="1">January</option>
<option value="2">February</option>
<option value="3">March</option>
<option value="4">April</option>
<option value="5">May</option>
<option value="6">June</option>
<option value="7">July</option>
<option value="8">August</option>
<option value="9">September</option>
<option value="10">October</option>
<option value="11">November</option>
<option value="12">December</option>
</select>
<select name="BirthDay">
<?php
for ($i=1; $i<=31; $i++)
{
echo "<option value='$i'>$i</option>";
}
?>
</select>
<select name="BirthYear">
<?php
for ($i=2011; $i>=1900; $i=$i-1)
{
echo "<option value='$i'>$i</option>";
}
?>
</select>
</td>
</tr>
<tr>
<td>Hire date:</td>
<td>
<select name="HireMonth">
<option value="1">January</option>
<option value="2">February</option>
<option value="3">March</option>
<option value="4">April</option>
<option value="5">May</option>
<option value="6">June</option>
<option value="7">July</option>
<option value="8">August</option>
<option value="9">September</option>
<option value="10">October</option>
<option value="11">November</option>
<option value="12">December</option>
</select>
<select name="HireDay">
<?php
for ($i=1; $i<=31; $i++)
{
echo "<option value='$i'>$i</option>";
}
?>
</select>
<select name="HireYear">
<?php
for ($i=2011; $i>=1992; $i=$i-1)
{
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
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 name="ReportsTo">
<option value="0">Choose...</option>
<option value="1">Nancy Davolio</option>
<option value="2">Andrew Fuller</option>
<option value="3">Janet Leverling</option>
<option value="4">Margaret Peacock</option>
<option value="5">Steven Buchanan</option>
<option value="6">Michael Suyama</option>
<option value="7">Robert King</option>
<option value="8">Laura Callahan</option>
<option value="9">Anne Dodsworth</option>
</select>
</td>
</tr>
<tr>
<td>Password:</td>
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
<td><input type="password" name="Password1" size="10"></td>
</tr>
<tr>
<td>Repeat Password:</td>
<td><input type="password" name="Password2" size="10"></td>
</tr>
<tr>
<td colspan="2"><input type="submit" value="Add Employee"></td>
</tr>
</table>
</form>
</body>
</html>
The above code, which contains some embedded PHP code, outputs a simple HTML form.
Its action page is ProcessEmployee.php, which will eventually contain PHP code to process
the submitted form.
Form Variables
Form variables are variables that are created when an HTML form is submitted using the post
method. These variables are stored in the $_POST superglobal array. Here are a few things
you should know about how HTML forms are processed:
1. If a text field or textarea is left blank, the variable is sent to the server with a value of
"" (empty string).
2. Select menus always send a variable to the server (unless they have been disabled in
some way).
3. If no radio button in a radio array is checked, no variable for that radio array is sent to
the server.
4. If a checkbox is not checked, no value is sent to the server. If it is checked, the default
value of "on" is sent unless otherwise set in the HTML.
5. If the submit button has a name (e.g, <input type="submit" name="Inserting"
value="Add Employee"/>), when that submit button is clicked a variable by that
name with the corresponding value will be sent to the server.
PHP Tutorial
String Manipulation
In this lesson, you will learn how to format strings and work with functions to manipulate
them. You will also learn the benefits and dangers of magic quotes.
Lesson Goals
Format strings.
Work with string manipulation functions.
Make strings safe for outputting to the browser.
Understand the benefits and dangers of magic quotes.
Formatting Strings
Concatenation
Concatenation is a programming word for adding strings together. In PHP, the concatenation
operator is a dot (.). Generally, concatenation is used to combine literal text with variables or
values returned from functions. The example below illustrates this.
Code Sample:
Strings/Demos/Concatenation.php
1
2
<!DOCTYPE HTML>
<html>
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
<head>
<meta charset="UTF-8">
<title>Concatenation</title>
</head>
<body>
<h1>Concatenation</h1>
<?php
$firstName = 'Paul';
$greeting = 'Hello';
echo $greeting . ' ' . $firstName . '!';
?>
<h2>Using Double Quotes to Avoid the Concatenation Operator</h2>
<?php
echo "$greeting $firstName!";
?>
<h2>Double quotes don't work when concatenating
the results of a function call</h2>
<?php
echo $greeting . ' ' . $firstName . '! Today is ' . date('l') . '.';
?>
</body>
</html>
As shown in the code, double quotes can be used to avoid using the concatenation operator.
This works for concatenating literal strings with variables, but it does not work for
concatenating values returned from functions. To do that, the function call must be outside of
any quotes and combined with the rest of the string using the concatenation operator. This
also is demonstrated in the code sample above.
String Manipulation Functions
Trimming Strings
Function Description
trim() Removes whitespace at beginning and end of a string.
ltrim() Removes whitespace at the beginning of a string.
rtrim() Removes whitespace at the end of a string.

Presentation
Function Description
htmlentities() Escapes all HTML entities.
nl2br() Inserts a <br /> tag before each newline character in a string.
strtoupper() Converts a string to uppercase.
strtolower() Converts a string to lowercase.
ucfirst() Converts the first character of a string to uppercase.
ucwords() Converts the first character of each word in a string to uppercase.

Converting Strings and Arrays
Function Description
explode() Splits a string into an array on a specified character or group of characters.
implode()
Converts an array into a string, placing a specified character or group of characters
between each array element.
join() Same as implode().

Substrings
Function Description
substr(str,pos)
Returns the substring from the character in
Substrings
Function Description
position pos to the end of the string.
substr(str,-len)
Returns the substring from len characters from
the end of the string to the end of the string.
substr(str,pos,len)
Returns a len length substring beginning with
the character in position pos.
substr(str,pos,-len)
Returns a substring beginning with the character
in position pos and chopping off the last len
characters of the string.
strstr(haystack,needle,before_needle)
If the third argument (before_needle) is
false (default), then it returns the part of the
haystack from the needle on.
If the third argument (before_needle) is
true, then it returns the part of the haystack
before the needle.
The needle can be a string or an integer (or a
number that can be converted to an integer).
stristr(haystack,needle,before_needle) Same as strstr(), but case insensitive.
strpos(haystack,needle)
Finds the position of the first occurrence of a
specified needle in a haystack (string).
The needle can be a string or an integer (or a
number that can be converted to an integer).
strrpos(haystack,needle)
Finds the position of the last occurrence of a
specified needle in a haystack (string).
The needle can be a string or an integer (or a
number that can be converted to an integer).
str_replace()
Replaces all occurrences of one string with
another string.

Comparing Strings
Function Description
Comparing Strings
Function Description
strcmp()
Compares two strings. Returns < 0 if str1 is less than str2, > 0 if str1 is greater than
str2, and 0 if they are equal.
strcasecmp() Like strcmp() but case insensitive.
strlen() Returns the length of a string.
Examples of String Functions
Below are some examples of string manipulation functions.
trim() and strtolower()
This example uses trim() and strtolower() to improve the form validation script.
Code Sample:
Strings/Demos/Greeting.php
1
2
3
4
5
6
7
8
9
10
11
12
13
<!DOCTYPE HTML>
<html>
<head>
<meta charset="UTF-8">
<title>Greeting Page</title>
</head>
<body>
<?php
$lastName = trim($_GET['LastName']);
$gender = strtolower(trim($_GET['Gender']));

if ($lastName == ' || $gender == ')
{
echo 'Error: You must fill out the form.
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
Please <a href="Greeting.html">try again</a>.';
}
else
{
switch($gender)
{
case 'male' :
echo "Hello Mr. $lastName!";
break;
case 'female' :
echo "Hello Ms. $lastName!";
break;
default :
echo "<b>$gender</b> is not a gender!";
}
}
?>
</body>
</html>
htmlentities() and nl2br()
The htmlentities() function is used to escape HTML entities, such as less than signs (<)
and greater than signs (>).
Another function called htmlspecialchars() is similar to htmlentities(). The differnce is
that htmlentities() escapes all HTML entities, while htmlspecialchars() only escapes the
most widely used. If you are interested in seeing the difference, take a look at
Strings/Demos/EscapingSpecialChars.php.
Take a look at the screenshot below to get an idea of why this is important.

Imagine if this form were submitted to the script below.
Code Sample:
Strings/Demos/HtmlEntitiesNotUsed.php
1
2
3
4
5
6
7
8
9
10
11
12
<!DOCTYPE HTML>
<html>
<head>
<meta charset="UTF-8">
<title>HTML Entities Processor</title>
</head>
<body>
<h1>HTML Entities Processor</h1>
<?php
echo $_POST['UserComments'];
?>
</body>
</html>
13
This would result in the JavaScript code being executed. This JavaScript code would create a
never-ending loop that popped up an alert over and over again. Although this would be pretty
annoying, there are much worse things users could do, such as make a remote procedure call
to execute a page on your server.
You can test this by opening Strings/Demos/HtmlEntitiesNotUsed.html and submitting the
form. You probably don't want to test with a never-ending loop though.
This can easily be fixed by changing the code to look like this:
Code Sample:
Strings/Demos/HtmlEntitiesUsed.php
1
2
3
4
5
6
7
8
9
10
11
12
13
<!DOCTYPE HTML>
<html>
<head>
<meta charset="UTF-8">
<title>HTML Entities Processor</title>
</head>
<body>
<h1>HTML Entities Processor</h1>
<?php
echo nl2br(htmlentities($_POST['UserComments']));
?>
</body>
</html>
This script uses htmlentities() to escape all the HTML entities and uses nl2br() to
convert newline characters to breaks. The resulting output looks like this:

And the resulting HTML source looks like this:
1
2
3
4
5
6
7
8
9
10
11
12
13
<html>
<head>
<title>HTML Entities Processor</title>
</head>
<body>
<h1>HTML Entities Processor</h1>
&lt;script language=&quot;javascript&quot;&gt;<br />
while (true)<br />
{<br />
alert(&quot;Try to get rid of me!&quot;);<br />
}<br />
&lt;/script&gt;</body>
</html>
explode()
The explode() function is used to convert a string to an array. The following form submits
to Explode.php, the code of which is shown below.

Code Sample:
Strings/Demos/Explode.php
1
2
3
4
5
6
7
8
9
10
11
12
13
<!DOCTYPE HTML>
<html>
<head>
<meta charset="UTF-8">
<title>Exploding Emails</title>
</head>
<body>
<?php
$emails = explode(';',$_POST['Emails']);
echo '<ol>';
foreach ($emails as $email)
{
echo '<li>' . trim($email) . '</li>';
}
14
15
16
17
18
echo '</ol>';
?>
</body>
</html>
Notice that the trim() function is used to trim the resulting elements of the array. This is
because the string is exploded on the semi-colon only. If the user adds additional whitespace
around the semi-colon, that whitespace will be part of the array element.
substr()
As shown earlier, the substr() function behaves differently depending on the values passed
to it. The following screenshot shows the effects of using substr().

Magic Quotes
There are two settings in the php.ini file that determine how PHP handles incoming data. The
settings are magic_quotes_gpc (on by default) and magic_quotes_runtime (off by default).
magic_quotes_gpc
The value of magic_quotes_gpc determines whether GET, POST and COOKIE data should
be escaped "automagically". If magic_quotes_gpc is set to 1, then single quotes, double
quotes and backslashes will be escaped with backslashes. In this case, if a user entered
"O'Reilly" as her last name, and your script returned that value to the browser (e.g, echo
$_POST['LastName'];), the value returned would read "O\'Reilly". You would need to strip
the backslashes by passing the value through the stripslashes() function (e.g, echo
stripslashes($_POST['LastName']);).
Although magic quotes can be useful, they can also cause confusion as the developer may not
know whether magic quotes are turned on or off. To check whether they are on, use the
get_magic_quotes_gpc() function as shown below.
1
2
3
4
5
6
7
8
if (get_magic_quotes_gpc())
{
echo stripslashes($_POST['LastName']);
}
else
{
echo $_POST['LastName'];
}
magic_quotes_runtime
The value of magic_quotes_runtime determines whether data returned from files and
databases should be escaped "automagically". It works similarly to magic_quotes_gpc.
Recommendation on Magic Quotes
Our recommendation on magic quotes is to turn them off in the php.ini file. You can easily
escape a string when you need to with the addslashes() function.
PHP Tutorial
Reusing Code and Writing Functions
Writing reusable code results in time and money savings, more consistent and bug free code,
and the ability to hide complex code from less seasoned developers.
Lesson Goals
Write reusable files and include them in multiple pages.
Write user-defined functions.
Create a library of user-defined form-validation and form-entry functions.
Including Files
PHP provides two common constructs for including files in web pages: require and
include. They are basically the same with one minor difference. require throws a fatal
error when it fails; whereas, include only gives a warning. If you need the included file to
continue to process the page, you should use require.
It is important to keep in mind that a PHP tag cannot start in a calling file and continue in an
included file. All PHP code in the included file must be nested in PHP tags.
require
require is not actually a function, but a language construct, so require statements can be
written in two ways:
Syntax
1
2
3
require(path_to_file);

require path_to_file;
path_to_file can be an absolute or a relative path.
require_once
require_once can be used just like require. The difference is that if the included file has
already been included by earlier code, it will not be re-included.
A Note on Security
If included files are under the web root, they can be accessed just as any other file can. If they
have an extension such as inc then the browser may display them as plain text. With other
extensions, the browser may attempt to download the file. If the included file is a PHP file
and a user navigates to it, the server will try to process the file and may return errors. As a
precaution, you may want to place your included files in a directory above or outside of the
web root. This will prevent users from accessing the files directly.
include_path directive
The php.ini contains an include_path directive, which takes a semi-colon delimited list of
paths to directories that PHP should look in for included files.
Here is a code sample that demonstrates how to include files using require.
Code Sample:
ReusingCode/Demos/Require.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
<!DOCTYPE HTML>
<html>
<head>
<meta charset="UTF-8">
<title>Including Files</title>
</head>
<body>
This text is on the main page.
<hr>
<?php
require 'Includes/Required.php';
?>
<hr>
<?php
require 'Includes/Required.inc';
?>
</body>
</html>
The above code is relatively straightforward. Require.php contains two included (required)
files: Required.php and Required.inc. Notice that there is PHP code inside of Required.inc,
which is executed. The extension of the included files does not affect how the code inside the
files will be executed.
auto_prepend_file and auto_append_file
The configuration file, php.ini, contains settings for automatically prepending and appending
files to every PHP script. These settings are auto_prepend_file and auto_append_file.
By default, they contain no values; however, they can be set to point to a files using absolute
paths as follows:
1
2
3
; Automatically add files before or after any PHP document.
auto_prepend_file = "c:/inetput/include/runbefore.inc"
auto_append_file = "c:/inetput/include/runafter.inc"
The auto_prepend_file directive can be used to include application-wide variables such as
database connection strings or common file paths. The auto_append_file directive can be
used for cleaning up code or for outputting debugging information to the browser.
Note that it is not possible to set different auto-prepend and auto-append files for different
directories or different scripts.
User Functions
User functions are used to make common tasks easier and to make code more modular and
easier to read. Unlike other identifiers in PHP, functions are case insensitive.
Defining and Calling Functions
A simple function is defined as follows.
Syntax
1
2
3
4
5
6
function myfunct()
{
do this;
do that;
do this other thing;
}
Like built-in functions, user functions can receive parameters. To define a function with
parameters, place receiving variables in the parentheses.
Syntax
1
2
3
4
5
function addNums($param1, $param2, $param3)
{
$sum = $param1 + $param2 + $param3;
echo 'The sum is ' . $sum;
}
User functions can also return values.
Syntax
1
2
3
4
5
function addNums($param1, $param2, $param3)
{
$sum = $param1 + $param2 + $param3;
return $sum;
}
User functions are called in the same way that built-in functions are. For example, the
following code calls the addNums() function to get the sum of three numbers.
Syntax
1
$total = addNums(1,3,5);
See ReusingCode/Demos/SimpleUDF.php to see the above code in action.
Default Values
You can make function parameters optional by assigning default values to them as shown in
the example below.
Code Sample:
ReusingCode/Demos/DefaultValues.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
<!DOCTYPE HTML>
<html>
<head>
<meta charset="UTF-8">
<title>Simple User-defined Function</title>
</head>

<body>
<?php
function addNums($param1=0, $param2=0, $param3=0)
{
$sum = $param1 + $param2 + $param3;
return $sum;
}

$Total = addNums(1,3);

echo $Total;
?>
</body>
</html>
In this case, if you don't pass a value into the function for one or more of the parameters, the
default value of 0 will be used. When defining a function, all required parameters should
precede optional parameters.
Variable Scope
In PHP, variables declared outside of functions are not available by default inside of
functions. The following code illustrates this:
Code Sample:
ReusingCode/Demos/LocalVars.php
1
2
3
4
5
6
7
8
9
10
11
<!DOCTYPE HTML>
<html>
<head>
<meta charset="UTF-8">
<title>Local Variables</title>
</head>

<body>
<?php
$a = 10;
$b = 5;

function incrNumBy()
{
12
13
14
15
16
17
18
19
20
21
22
$a += $b;
}
incrNumBy(); //results in two warnings as $a and $b are
//undefined in the function scope
echo $a; //outputs 10 to the browser
?>
</body>
</html>
To make the variables available to the function, they must be declared within the function as
global variables using the global keyword.
Code Sample:
ReusingCode/Demos/GlobalVars.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
<!DOCTYPE HTML>
<html>
<head>
<meta charset="UTF-8">
<title>Global Variables</title>
</head>

<body>
<?php
$a = 10;
$b = 5;

function incrNumBy()
{
global $a,$b;
$a += $b;
}
incrNumBy();
echo $a; //outputs 15 to the browser
?>
</body>
</html>
By Reference vs. By Value
By default, variables are passed to functions by value, meaning that the function's receiving
variables get copies of the values received rather than pointers to them. If the receiving
variables are modified, the passed variables remain unaffected. The following code illustrates
this.
Code Sample:
ReusingCode/Demos/ByValue.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
<!DOCTYPE HTML>
<html>
<head>
<meta charset="UTF-8">
<title>By Value</title>
</head>
<body>
<?php
$a = 10;
$b = 5;
function incrNumBy($num,$incr)
{
$num += $incr;
}

incrNumBy($a,$b);
echo $a; //outputs 10 to the browser
?>
</body>
</html>
The above code outputs "10" to the browser. Although $num was incremented by 5, $a was
unaffected by the function call. To pass a variable by reference, put an ampersand (&) before
the parameter in the function definition.
Code Sample:
ReusingCode/Demos/ByReference.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
<!DOCTYPE HTML>
<html>
<head>
<meta charset="UTF-8">
<title>By Reference</title>
</head>
<body>
<?php
$a = 10;
$b = 5;
function incrNumBy(&$num,$incr)
{
$num += $incr;
}

incrNumBy($a,$b);
echo $a; //outputs 15 to the browser
?>
</body>
</html>
19
20
This time the function outputs "15" because $num references the variable $a itself. So, any
change in $num will affect $a.
Form Processing
Processing forms generally involves the following tasks:
1. Writing the HTML code to output the form.
2. Writing validation code to validate the form entries after the form is submitted.
3. Writing code to output errors if there are any.
4. Writing code to process the form entries if they are all valid.
Although these tasks are all separate, some are dependent on others. For example, if errors
are found when the form is submitted, it is nice to re-output the form, but the HTML code
may be different from the original form as you will likely want to include error messages and
also echo the values that the user entered. It's very easy to get your code all tangled up
resulting in what is known as spaghetti code. We will now examine one approach for
organizing code using functions and includes to make it easier to maintain.
Code Organization
Application Flow
The application we are building works like this:
1. When the user first visits, she is presented with a form to fill out.
2. If she fills out the form...
o Correctly
She is presented with another form to confirm her entries.
After confirming her entries, the data will be processed (e.g, entered
into a database or emailed to someone).
o Incorrectly
She is presented with the same form with her entries in tact and
appropriate error messages displayed.
Application Files
To make our code easier to maintain, we will organize it as follows:
1. Includes/init.php - Initializes and sets some variables.
2. AddEmployee.php - Contains code that defines the flow of the application.
3. Includes/EmployeeForm.php - Contains code to display entry form.
4. Includes/ProcessEmployee.php - Contains code to process the original form entry. If
there are errors, they will be displayed on the page. If there are no errors, the user's
entries will be displayed with a "Confirm" button.
5. Includes/InsertEmployee.php - Contains code to insert the employee into a database.
(This file is currently empty.)
6. Includes/fnFormPresentation.php - Contains a library of functions for presenting form
fields.
7. Includes/fnFormValidation.php - Contains a library of functions for validating form
entries.
8. Includes/fnStrings.php - Contains a couple of useful string functions.
9. Includes/fnDates.php - Contains a useful date function.
We will examine each of these files.
Code Sample:
ReusingCode/Demos/Includes/init.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
<?php
$showForm = true;

$mgrEntries = array();
$mgrEntries[1]='Nancy Davolio';
$mgrEntries[2]='Andrew Fuller';
$mgrEntries[3]='Janet Leverling';
$mgrEntries[4]='Margaret Peacock';
$mgrEntries[5]='Steven Buchanan';
$mgrEntries[6]='Michael Suyama';
$mgrEntries[7]='Robert King';
$mgrEntries[8]='Laura Callahan';
$mgrEntries[9]='Anne Dodsworth';

$errors = array();
$dbEntries = array( 'FirstName'=>',
'LastName'=>',
'Email'=>',
'Title'=>',
'TitleOfCourtesy'=>',
'Address'=>',
'City'=>',
'Region'=>',
'PostalCode'=>',
'Country'=>',
'HomePhone'=>',
'Extension'=>',
'Notes'=>',
'ReportsTo'=>',
'Password'=>',
'Email'=>',
'BirthMonth'=>1,
'BirthDay'=>1,
'BirthYear'=>date('Y'),
'HireMonth'=>1,
'HireDay'=>1,
'HireYear'=>date('Y'));
$browserEntries = array();
?>
37
38
39
This file sets several variables used throughout the application.
Code Sample:
ReusingCode/Demos/AddEmployee.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
<?php
require 'Includes/fnFormValidation.php';
require 'Includes/fnFormPresentation.php';
require 'Includes/fnStrings.php';
require 'Includes/fnDates.php';
require 'Includes/init.php';
?>
<!DOCTYPE HTML>
<html>
<head>
<meta charset="UTF-8">
<title>Add Employee</title>
<style type="text/css">
.Error {color:red; font-size:smaller;}
</style>
</head>
<body>
<?php
require 'Includes/Header.php';

if (array_key_exists('Submitted',$_POST))
{
require 'Includes/ProcessEmployee.php';
}
elseif (array_key_exists('Confirmed',$_POST))
{
require 'Includes/InsertEmployee.php';
}

if ($showForm)
{
require 'Includes/EmployeeForm.php';
}

require 'Includes/Footer.php';
?>
</body>
</html>
The code is relatively easy to read. Things to note:
1. At the very top, we include several files we will need for the application.
2. In the body, we include:
o our header and footer files.
o code that checks which, if either, form was submitted and includes the
appropriate file.
o code that checks whether or not to show the main form. The form will be
shown if:
it has not yet been submitted.
it has been submitted with errors.
Code Sample:
ReusingCode/Demos/Includes/fnDates.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
<?php
/********* DATE FUNCTIONS *********/

/*
Function Name: monthAsString
Arguments: $m
Returns:
month as string
*/
function monthAsString($m)
{
$months = array();
$months[] = 'January';
$months[] = 'February';
$months[] = 'March';
$months[] = 'April';
$months[] = 'May';
$months[] = 'June';
$months[] = 'July';
$months[] = 'August';
$months[] = 'September';
$months[] = 'October';
$months[] = 'November';
$months[] = 'December';

return $months[$m-1];
}
?>
This file includes a simple function for getting the name of a month (e.g, February) given the
month number (e.g, 2).
Code Sample:
ReusingCode/Demos/Includes/fnStrings.php
1
<?php
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
/********** STRING FUNCTIONS *********/
/*
Function Name: browserString
Arguments: $string
Returns:
trimmed and escaped string for browser output
*/
function browserString($string)
{
return nl2br(trim(htmlentities($string)));
}

/*
Function Name: dbString
Arguments: $string
Returns:
trimmed and escaped string for database entry
*/
function dbString($email)
{
if (get_magic_quotes_gpc())
{
return trim ($email);
}
else
{
return addslashes(trim($email));
}
}

?>
This file includes functions for cleaning up strings for browser and database output.
Code Sample:
ReusingCode/Demos/Includes/fnFormPresentation.php
1
2
3
4
5
6
7
8
9
10
11
12
13
<?php
/********* FORM PRESENTATION FUNCTIONS *********/

/*
Function Name: textEntry
Arguments: $display,$name,$entries,$errors,$size?
Returns:
one table row as string
*/
function textEntry($display,$name,$entries,$errors,$size=15)
{
$returnVal = "
<tr>
<td>$display:</td>
<td>
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
<input type='text' name='$name' size='$size'
value=\"" . browserString($entries[$name]) . "\">";

if (array_key_exists($name,$errors))
{
$returnVal .= '<span class="Error" style="white-space:nowrap">*
' .
$errors[$name] .
'</span>';
}

$returnVal .= "</td>
</tr>";

return $returnVal;
}

/*
Function Name: pwEntry
Arguments: $pw1,$pw2,$errors,$size?
Returns:
table rows as string
*/
function pwEntry($pw1,$pw2,$errors,$size=10)
{
$returnVal = "
<tr>
<td>Password:</td>
<td>
<input type='password' name='$pw1' size='$size'>
</td>
</tr>
<tr>
<td>Repeat Password:</td>
<td>
<input type='password' name='$pw2' size='$size'>
</td>
</tr>";

if (array_key_exists('Password',$errors))
{
$returnVal .= addErrorRow('Password',$errors);
}
return $returnVal;
}

/*
Function Name: textAreaEntry
Arguments: $display,$name,$entries,$errors,$cols?,$rows?
Returns:
table rows as string
*/
function textAreaEntry($display,$name,$entries,$errors,$cols=45,$rows=5)
{
$returnVal = "
<tr>
<td colspan='2'>$display:</td>
</tr>
<tr>
<td colspan='2'>
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
<textarea name='$name' cols='$cols' rows='$rows'>";
$returnVal .= $entries[$name];
$returnVal .= "</textarea>
</td>
</tr>";

if (array_key_exists($name,$errors))
{
$returnVal .= addErrorRow($name,$errors);
}
return $returnVal;
}

/*
Function Name: radioEntry
Arguments: $display,$name,$entries,$errors,$values
Returns:
table rows as string
*/
function radioEntry($display,$name,$entries,$errors,$values)
{
$returnVal = "
<tr>
<td>$display:</td>
<td>$name</td>
</tr>";

return $returnVal;
}

/*
Function Name: selectEntry
Arguments: $display,$name,$entries,$errors,$selected?
Returns:
table rows as string
*/
function selectEntry($display,$name,$options,$errors,$selected=0)
{
$returnVal = "<tr>
<td>$display:</td>
<td>
<select name='$name'>
<option value='0'>Choose one...</option>";
$returnVal .= "</select>
</td>
</tr>";
return $returnVal;
}

/*
Function Name: selectDateEntry
Arguments: $display,$namePre,$month,$day,$year
Returns:
table rows as string
*/
function selectDateEntry($display,$namePre,$month,$day,$year,$errors)
{
$returnVal = "<tr>
<td>$display:</td>
<td>
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
<select name='$namePre" . "Month'>";
for ($i=1; $i<=12; $i++)
{
if ($i == $month)
{
$returnVal .= "<option value='$i' selected>";
}
else
{
$returnVal .= "<option value='$i'>";
}
$returnVal .= monthAsString($i) . '</option>';
}
$returnVal .= "</select>
<select name='$namePre" . "Day'>";
for ($i=1; $i<=31; $i++)
{
if ($i == $day)
{
$returnVal .= "<option value='$i' selected>";
}
else
{
$returnVal .= "<option value='$i'>";
}
$returnVal .= "$i</option>";
}
$returnVal .= "</select>
<select name='$namePre" . "Year'>";
for ($i=date('Y'); $i>=1900; $i=$i-1)
{
if ($i == $year)
{
$returnVal .= "<option value='$i' selected>";
}
else
{
$returnVal .= "<option value='$i'>$i</option>";
}
$returnVal .= "$i</option>";
}
$returnVal .= '</select>
</td>
</tr>';

if (array_key_exists($namePre . 'Date',$errors))
{
$returnVal .= addErrorRow($namePre . 'Date',$errors);
}
return $returnVal;
}

/*
Function Name: addErrorRow
Arguments: $name
Returns:
table row as string
*/
function addErrorRow($name,$errors)
{
$errorRow = '<tr><td colspan="2" class="Error">* ' .
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
$errors[$name] .
'</td></tr>';
return $errorRow;
}
?>
This file contains functions for presenting form entries. Several of these functions are
complete, but there are a couple that need to be finished. This will be part of the next
exercise.
Code Sample:
ReusingCode/Demos/Includes/fnFormValidation.php
1
2
3
4
5
<?php
/********* FORM VALIDATION FUNCTIONS *********/

/*
Function Name: checkLength
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
Arguments: $text,$min?,$max?,$trim?
Returns:
false if $text has fewer than $min characters
false if $text has more than $max characters
true otherwise
*/
function checkLength($text,$min=1,$max=10000,$trim=true)
{
if ($trim)
{
$text = trim($text);
}
if (strlen($text) < $min || strlen($text) > $max)
{
return false;
}
return true;
}

/*
Function Name: checkEmail
Arguments: $email
Returns:
false if $email has fewer than 6 characters
false if $email does not contain @ symbol
false if $email does not contain a period (.)
false if the last @ symbol comes after the last period (.)
true otherwise
*/
function checkEmail($email)
{
return true;
}

/*
Function Name: checkPassword
Arguments: $pw1,$pw2
Returns:
false if $pw1 has fewer than 6 characters
false if $pw1 has more than 12 characters
false if $pw1 and $pw2 do not match
true otherwise
*/
function checkPassword($pw1,$pw2)
{
return true;
}
?>
This file contains functions for validating form entries. One of these functions is complete,
but there are a couple that need to be finished. This will also be part of the next exercise.
Code Sample:
ReusingCode/Demos/Includes/EmployeeForm.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
<h1 align="center">Add Employee</h1>
<form method="post" action="AddEmployee.php">
<input type="hidden" name="Submitted" value="true">
<table align="center" border="1" width="500">
<?php
echo textEntry('First name','FirstName',$dbEntries,$errors,15);
echo textEntry('Last name','LastName',$dbEntries,$errors,15);
echo textEntry('Email','Email',$dbEntries,$errors,25);
echo textEntry('Title','Title',$dbEntries,$errors,30);
echo radioEntry('Title of Courtesy','TitleOfCourtesy',
$dbEntries,$errors,
array('Dr.','Mr.','Mrs.','Ms.'));
echo selectDateEntry('Birth date','Birth',
$dbEntries['BirthMonth'],
$dbEntries['BirthDay'],
$dbEntries['BirthYear'],
$errors);
echo selectDateEntry('Hire date','Hire',
$dbEntries['HireMonth'],
$dbEntries['HireDay'],
$dbEntries['HireYear'],
$errors);
echo textEntry('Address','Address',$dbEntries,$errors,50);
echo textEntry('City','City',$dbEntries,$errors,30);
echo textEntry('Region','Region',$dbEntries,$errors,2);
echo textEntry('Postal Code','PostalCode',$dbEntries,$errors,10);
echo textEntry('Country','Country',$dbEntries,$errors,5);
echo textEntry('Home phone','HomePhone',$dbEntries,$errors,15);
echo textEntry('Extension','Extension',$dbEntries,$errors,5);
echo textAreaEntry('Notes','Notes',$dbEntries,$errors,50,3);
echo selectEntry('Manager','ReportsTo',$mgrEntries,
$errors,$dbEntries['ReportsTo']);
echo pwEntry('Password1','Password2',$errors,10);
?>
<tr>
<td colspan="2"><input type="submit" value="Add Employee"></td>
</tr>
</table>
</form>
This file creates the entry form. Notice that it creates entry rows through calls to functions in
the fnFormPresentation.php file. This allows us to easily incorporate error handling and error
messages into the form entries without making the HTML form itself difficult to maintain.
Code Sample:
ReusingCode/Demos/Includes/ProcessEmployee.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
<?php
$dbEntries['FirstName'] = dbString($_POST['FirstName']);
$dbEntries['LastName'] = dbString($_POST['LastName']);
$dbEntries['Title'] = ucwords(dbString($_POST['Title']));
$dbEntries['Address'] = dbString($_POST['Address']);
$dbEntries['City'] = dbString($_POST['City']);
$dbEntries['Region'] = dbString($_POST['Region']);
$dbEntries['PostalCode'] = dbString($_POST['PostalCode']);
$dbEntries['Country'] = dbString($_POST['Country']);
$dbEntries['HomePhone'] = dbString($_POST['HomePhone']);
$dbEntries['Extension'] = dbString($_POST['Extension']);
$dbEntries['Notes'] = dbString($_POST['Notes']);
$dbEntries['ReportsTo'] = $_POST['ReportsTo'];
$dbEntries['Password'] = dbString($_POST['Password1']);
$dbEntries['Email'] = dbString($_POST['Email']);
$dbEntries['BirthMonth'] = dbString($_POST['BirthMonth']);
$dbEntries['BirthDay'] = dbString($_POST['BirthDay']);
$dbEntries['BirthYear'] = dbString($_POST['BirthYear']);
$dbEntries['HireMonth'] = dbString($_POST['HireMonth']);
$dbEntries['HireDay'] = dbString($_POST['HireDay']);
$dbEntries['HireYear'] = dbString($_POST['HireYear']);

if (!checkLength($_POST['FirstName']))
{
$errors['FirstName'] = 'First name omitted.';
}
else
{
$browserEntries['FirstName'] =
browserString($_POST['FirstName']);
}

if (!checkLength($_POST['LastName']))
{
$errors['LastName'] = 'Last name omitted.';
}
else
{
$browserEntries['LastName'] = browserString($_POST['LastName']);
}

if (!checkLength($_POST['Title']))
{
$errors['Title'] = 'Title omitted.';
}
else
{
$browserEntries['Title'] =
ucwords(browserString($_POST['Title']));
}

if ( array_key_exists('TitleOfCourtesy',$_POST) )
{
$browserEntries['TitleOfCourtesy'] =
browserString($_POST['TitleOfCourtesy']);
$dbEntries['TitleOfCourtesy'] =
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
dbString($_POST['TitleOfCourtesy']);
}
else
{
$errors['TitleOfCourtesy'] = 'Title of Courtesy not selected.';
}

if
(!checkdate($_POST['BirthMonth'],$_POST['BirthDay'],$_POST['BirthYear'])
)
{
$errors['BirthDate'] = 'Birth date is not a valid date.';
}

if
(!checkdate($_POST['HireMonth'],$_POST['HireDay'],$_POST['HireYear']))
{
$errors['HireDate'] = 'Hire date is not a valid date.';
}

if (!checkLength($_POST['Address'],5,200))
{
$errors['Address'] = 'Address omitted.';
}
else
{
$browserEntries['Address'] = browserString($_POST['Address']);
}

if (!checkLength($_POST['City'],1,100))
{
$errors['City'] = 'City omitted.';
}
else
{
$browserEntries['City'] = browserString($_POST['City']);
}

if (!checkLength($_POST['Region'],2,2) &&
!checkLength($_POST['Region'],0,0))
{
$errors['Region'] = 'Region name must be two characters.';
}
else
{
$browserEntries['Region'] = browserString($_POST['Region']);
}

if (!checkLength($_POST['PostalCode']))
{
$errors['PostalCode'] = 'Postal Code omitted.';
}
else
{
$browserEntries['PostalCode'] =
browserString($_POST['PostalCode']);
}

if (!checkLength($_POST['Country']))
{
98
99
10
0
10
1
10
2
10
3
10
4
10
5
10
6
10
7
10
8
10
9
11
0
11
1
11
2
11
3
11
4
11
5
11
6
11
7
11
8
11
9
12
0
12
1
12
2
12
3
$errors['Country'] = 'Country omitted.';
}
else
{
$browserEntries['Country'] = browserString($_POST['Country']);
}

if (!checkLength($_POST['HomePhone'],10,15))
{
$errors['HomePhone'] = 'Home phone must be between 10 and 15
characters.';
}
else
{
$browserEntries['HomePhone'] =
browserString($_POST['HomePhone']);
}

if (!checkLength($_POST['Extension'],3,5))
{
$errors['Extension'] = 'Extension must be between 3 and 5
characters.';
}
else
{
$browserEntries['Extension'] =
browserString($_POST['Extension']);
}

if (!checkLength($_POST['Notes'],0,100))
{
$errors['Notes'] = 'Notes must be fewer than 100 characters:<br>
<span style="color:blue; font-weight:normal">' .
browserString(substr($_POST['Notes'],0,100)) .
'</span><span style="color:red; font-weight:normal;
text-decoration:line-through;">' .
browserString(substr($_POST['Notes'],100)) .
'</span>';
}
else
{
$browserEntries['Notes'] = browserString($_POST['Notes']);
}

if ($_POST['ReportsTo'] == 0)
{
$errors['ReportsTo'] = 'Manager not selected.';
}
else
{
$browserEntries['ReportsTo'] = $_POST['ReportsTo'];
}

if ( !checkPassword($_POST['Password1'],$_POST['Password2']) )
{
$errors['Password'] = 'Passwords do not match or are not the
right length.';
}
else
{
12
4
12
5
12
6
12
7
12
8
12
9
13
0
13
1
13
2
13
3
13
4
13
5
13
6
13
7
13
8
13
9
14
0
14
1
14
2
14
3
14
4
14
5
14
6
14
7
14
8
$browserEntries['Password'] =
browserString($_POST['Password1']);
}

if ( !checkEmail($_POST['Email']) )
{
$errors['Email'] = 'Email is invalid.';
}
else
{
$browserEntries['Email'] = browserString($_POST['Email']);
}
?>
<?php
if (!count($errors))
{
$showForm = false;
?>
<form method="post" action="AddEmployee.php">
<input type="hidden" name="Confirmed" value="true">
<?php
echo '<h2>Confirm Entries</h2>';
echo '<ol>';
foreach ($browserEntries as $key=>$entry)
{
if ($key=='ReportsTo')
{
echo "<li><b>Manager:</b> $mgrEntries[$entry]</li>";
}
else
{
echo "<li><b>$key:</b> $entry</li>";
}
}
echo '</ol>';

foreach ($dbEntries as $key=>$entry)
{
?>
<input type="hidden" name="<?php echo $key ?>"
value="<?php echo $entry ?>">
<?php
}
?>
<input type="submit" value="Confirm">
</form>
<?php
}
else
{
$dbEntries = $_POST;
}
?>
14
9
15
0
15
1
15
2
15
3
15
4
15
5
15
6
15
7
15
8
15
9
16
0
16
1
16
2
16
3
16
4
16
5
16
6
16
7
16
8
16
9
17
0
17
1
17
2
17
3
17
4
17
5
17
6
17
7
17
8
17
9
18
0
18
1
18
2
18
3
18
4
18
5
18
6
18
7
18
8
18
9
19
0
19
1
19
2
19
3
19
4
19
5
19
6
19
7
19
8
19
9
20
0
20
1
20
2
20
3
20
4
20
5
20
6
20
7
20
8
20
9
21
0
21
1
21
2
21
3
21
4
This file contains code for processing the form entries. It makes use of functions in the
fnFormValidation.php file for validating entries. If no errors are found, it sets the boolean
$showForm to false, so that the original form will not be displayed and it outputs all the
entries (made browser-safe) to the browser for confirmation. If errors are found, it adds them
to the $errors array, which is passed into the form presentation functions, so that they can
return code for displaying the errors. If there are errors, the boolean $showForm is left as
true, so that the original form is redisplayed.
Code Sample:
ReusingCode/Demos/Includes/InsertEmployee.php
1
TO DO LATER
This file will eventually contain code for inserting the employee information into the
database.
PHP Tutorial
Managing Data
In this lesson, you will learn how to access a database in PHP.
Lesson Goals
Retrieve and safely display records from a database.
Insert new records into a database.
Update existing records in a database.
Querying a Database
The steps for querying a database in a PHP script are as follows:
1. Connect to the database.
2. Send query to the database.
3. Retrieve and store results sent back from the database.
4. Output the results of the query to the browser.
5. Free up resources and disconnect from the database.
mysqli() Overview
New in PHP5 is the mysqli library, which works with MySQL versions 4.1.3 and above and
takes advantage of a new faster connection protocol in MySQL. The mysqli library provides
two interfaces: an object-oriented interface and a procedural interface. The following two
scripts use the two different interfaces to accomplish the same result.
Code Sample:
ManagingData/Demos/SimpleQuery-OO.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
<!DOCTYPE HTML>
<html>
<head>
<meta charset="UTF-8">
<title>Simple Query - OO</title>
</head>
<body>
<?php
@$db = new mysqli('localhost','root','pwdpwd','Northwind');
if (mysqli_connect_errno())
{
echo 'Cannot connect to database: ' . mysqli_connect_error();
}
else
{
$query = 'SELECT * FROM Employees';
$result = $db->query($query);
$numResults = $result->num_rows;
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49

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->fetch_assoc())
{
echo '<tr>';
echo '<td>' . $row['FirstName'] . '</td>';
echo '<td>' . $row['LastName'] . '</td>';
echo '<td>' . $row['Title'] . '</td>';
echo '<td>' . $row['Email'] . '</td>';
echo '<td align="right">x' . $row['Extension'] . '</td>';
echo '</tr>';
}
?>
</table>
<?php
$result->free();
$db->close();
}
?>
</body>
</html>
Code Sample:
ManagingData/Demos/SimpleQuery-Procedural.php
1
2
3
4
5
6
7
8
9
10
11
<!DOCTYPE HTML>
<html>
<head>
<meta charset="UTF-8">
<title>Simple Query - Procedural</title>
</head>
<body>
<?php
@$db = mysqli_connect('localhost','root','pwdpwd','Northwind');
if (mysqli_connect_errno())
{
echo 'Cannot connect to database: ' . mysqli_connect_error();
}
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
else
{
$query = 'SELECT * FROM Employees';
$result = mysqli_query($db,$query);
$numResults = mysqli_num_rows($result);

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 = mysqli_fetch_assoc($result))
{
echo '<tr>';
echo '<td>' . $row['FirstName'] . '</td>';
echo '<td>' . $row['LastName'] . '</td>';
echo '<td>' . $row['Title'] . '</td>';
echo '<td>' . $row['Email'] . '</td>';
echo '<td align="right">x' . $row['Extension'] . '</td>';
echo '</tr>';
}
?>
</table>
<?php
mysqli_free_result($result);
mysqli_close($db);
}
?>
</body>
</html>
1. To connect to the database, we use:
o Object-oriented: @$db = new
mysqli('localhost','root','pwdpwd','Northwind');
o Procedural: @$db =
mysqli_connect('localhost','root','pwdpwd','Northwind');
2. To see if the connection was successful we check mysqli_connect_errno(), which
returns an error number if there is a connection error or 0 if there is no error. If an
error occurs, we output a message with mysqli_connect_error(). We use the
procedural interface in both cases, because a connection object doesn't get created if
the connection fails.
3. To send the query to the database and store the results in a variable, we use:
o Object-oriented: $result = $db->query($query);
o Procedural: $result = mysqli_query($db,$query);
4. To output the results of the query, we use:
o Object-oriented:
1
2
3
4
5
6
7
8
9
while ($row = $result->fetch_assoc()) {
echo "<tr>";
echo "<td>" . $row['FirstName'] . "</td>";
echo "<td>" . $row['LastName'] . "</td>";
echo "<td>" . $row['Title'] . "</td>";
echo "<td>" . $row['Email'] . "</td>";
echo "<td align='right'>x" . $row['Extension'] .
"</td>";
echo "</tr>";
}
o Procedural:
1
2
3
4
5
6
7
8
9
while ($row = mysqli_fetch_assoc($result)) {
echo "<tr>";
echo "<td>" . $row['FirstName'] . "</td>";
echo "<td>" . $row['LastName'] . "</td>";
echo "<td>" . $row['Title'] . "</td>";
echo "<td>" . $row['Email'] . "</td>";
echo "<td align='right'>x" . $row['Extension'] .
"</td>";
echo "</tr>";
}
5. To free up resources and disconnect from the database, we use:
o Object-oriented:
1
2
$result->free();
$db->close();
o Procedural:
1
2
mysqli_free_result($result);
mysqli_close($db);
As you can see, the two scripts are pretty similar. We will use the object-oriented interface in
future examples.
mysqli Methods and Properties
Connection Methods and Properties
Object-
oriented
Procedural Description
new mysqli() mysqli_connect() Connects to a MySQL server.

mysqli_connect_errno() Returns connection error number or 0 if there's
Connection Methods and Properties
Object-
oriented
Procedural Description
no error.

mysqli_connect_error()
Returns connection error message.
$db-
>host_info
mysqli_get_host_info()
Returns information on the connection.

Query Functions
Object-oriented Procedural Description
$db->query() mysqli_query()
Sends a query to the database and returns
results.
$db-
>multi_query()
mysqli_multi_query()
Sends multiple queries to the database and
returns results.

Fetch Functions
Object-oriented Procedural Description
$result-
>fetch_row()
mysqli_fetch_row()
Returns a result row from a query result
object or resource as an indexed array.
$result-
>fetch_assoc()
mysqli_fetch_assoc()
Returns a result row from a query result
object or resource as an associative array.
$result-
>fetch_object()
mysqli_fetch_object()
Returns a result row from a query result
object or resource as an object.
Inserting and Updating Records
Records are inserted and updated with SQL queries using the same mysqli library we used to
generate a report. Review the following scripts.
Code Sample:
ManagingData/Demos/EmployeeReport.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
---- C O D E O M I T T E D ----
<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>' . $row['FirstName'] . '</td>';
echo '<td>' . $row['LastName'] . '</td>';
echo '<td>' . $row['Title'] . '</td>';
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
echo '<td>' . $row['Email'] . '</td>';
echo '<td align="right">x' . $row['Extension'] . '</td>';
echo '<td><form method="post" action="EditEmployee.php">
<input type="hidden" name="EmployeeID"
value="' . $row['EmployeeID'] . '">
<input type="submit" name="Editing" value="Edit">
</form></td>';
echo '</tr>';
}
?>
</table>
---- C O D E O M I T T E D ----
This file is similar to the SimpleQuery examples we saw earlier in this lesson. The only
difference is that each row now has an edit form in the last column, which sends the
employee's EmployeeID to EditEmployee.php.
Code Sample:
ManagingData/Demos/EditEmployee.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
<?php
require 'Includes/fnFormValidation.php';
require 'Includes/fnFormPresentation.php';
require 'Includes/fnStrings.php';
require 'Includes/fnDates.php';
require 'Includes/init.php';
@$db = new mysqli('localhost','root','pwdpwd','Northwind');
if (mysqli_connect_errno())
{
echo 'Cannot connect to database: ' . mysqli_connect_error();
}
?>
<!DOCTYPE HTML>
<html>
<head>
<meta charset="UTF-8">
<title>Edit Employee</title>
<style type="text/css">
.Error {color:red; font-size:smaller;}
</style>
</head>
<body>
<?php
require 'Includes/Header.php';

if (array_key_exists('Updating',$_POST))
{
require 'Includes/ProcessEmployee.php';
}

require 'Includes/EmployeeData.php';
require 'Includes/EmployeeForm.php';
28
29
30
31
32
33
34
35
36
37
38
39

require 'Includes/Footer.php';

$db->close();
?>
</body>
</html>
This file is similar to the AddEmployee.php file we worked on earlier in the course. This one
goes a step further though by connecting to the database to retrieve data to populate the form.
It works as follows:
1. At the very top, we include several files we will need for the application and we
connect to the database.
2. In the body, we include:
o our header and footer files.
o code that checks whether the user has already made updates and, if so,
includes the processing file.
o the file with code to retrieve the specified employee's data.
o the file with code to display the filled-in form.
Code Sample:
ManagingData/Demos/Includes/EmployeeData.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
<?php
$employeeID = $_POST['EmployeeID'];

$query = "SELECT FirstName, LastName, Title,
TitleOfCourtesy, Email,
MONTH(BirthDate) AS BirthMonth,
DAYOFMONTH(BirthDate) AS BirthDay,
YEAR(BirthDate) AS BirthYear,
MONTH(HireDate) AS HireMonth,
DAYOFMONTH(HireDate) AS HireDay,
YEAR(HireDate) AS HireYear,
Address, City, Region, PostalCode, Country,
HomePhone, Extension, Notes, ReportsTo, Password
FROM Employees
WHERE EmployeeID = $employeeID";
$result = $db->query($query);
$dbEntries = $result->fetch_assoc();

$result->free();
?>
This file contains the query that selects the specified employee's data and populates the
$dbEntries array with the results.
Code Sample:
ManagingData/Demos/Includes/fnStrings.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
<?php
/********** STRING FUNCTIONS *********/
---- C O D E O M I T T E D ----

/*
Function Name: dbString
Arguments: $string
Returns:
trimmed and escaped string for database entry
*/
function dbString($string)
{
$string=trim($string);
if (get_magic_quotes_gpc())
{
return $string;
}
else
{
return addslashes($string);
}
}
?>
This file is the same as the fnStrings.php file we saw before except that the dbString()
function has been updated. It now checks to see if magic quotes are turned on. If they are,
then form entries will be made database-safe "automagically", so it just returns the trimmed
string. If they are not, then it uses addslashes() to make the string safe for database queries.
Code Sample:
ManagingData/Demos/Includes/fnFormValidation.php
1
2
3
4
5
6
7
8
9
10
11
<?php
/********* FORM VALIDATION FUNCTIONS *********/
---- C O D E O M I T T E D ----
/*
Function Name: checkPassword
Arguments: $pw1,$pw2,$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,$checkLen=true)
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
{
$pw1 = trim($pw1);
$pw2 = trim($pw2);
if ($checkLen)
{
return checkLength($pw1,6,12) && strcmp($pw1,$pw2) == 0;
}
else
{
return strcmp($pw1,$pw2) == 0;
}
}
?>
This file is the same as the fnFormValidation.php file we saw before except that the
checkPassword() function now takes an additional parameter: $checkLen, which when set
to false, will prevent the function from returning false if a blank password is entered.
Code Sample:
ManagingData/Demos/Includes/ProcessEmployee.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
<?php
$dbEntries = $_POST;
foreach ($dbEntries as &$entry)
{
$entry = dbString($entry);
}
$dbEntries['Title'] = ucwords($dbEntries['Title']);
---- C O D E O M I T T E D ----
if (array_key_exists('EmployeeID',$_POST))
{
$pwCheckLen = false;
}
else
{
$pwCheckLen = true;
}

if (
!checkPassword($_POST['Password1'],$_POST['Password2'],$pwCheckLen) )
{
$errors['Password'] = 'Passwords do not match or are not the
right length.';
}
else
{
$browserEntries['Password'] = browserString($_POST['Password1']);
}
---- C O D E O M I T T E D ----
?>
<?php
if (!count($errors) && array_key_exists('EmployeeID',$_POST))
{
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
$employeeID = $_POST['EmployeeID'];
$query = "UPDATE Employees
SET FirstName='" . $dbEntries['FirstName'] . "',
LastName='" . $dbEntries['LastName'] . "',
Title='" . $dbEntries['Title'] . "',
TitleOfCourtesy='" . $dbEntries['TitleOfCourtesy'] . "',
Email='" . $dbEntries['Email'] . "',
BirthDate='" . $dbEntries['BirthYear'] . '-' .
$dbEntries['BirthMonth'] . '-' .
$dbEntries['BirthDay'] . "',
HireDate='" . $dbEntries['HireYear'] . '-' .
$dbEntries['HireMonth'] . '-' .
$dbEntries['HireDay'] . "',
Address='" . $dbEntries['Address'] . "',
City='" . $dbEntries['City'] . "',
Region='" . $dbEntries['Region'] . "',
PostalCode='" . $dbEntries['PostalCode'] . "',
Country='" . $dbEntries['Country'] . "',
HomePhone='" . $dbEntries['HomePhone'] . "',
Extension='" . $dbEntries['Extension'] . "',
Notes='" . $dbEntries['Notes'] . "',
ReportsTo=" . $dbEntries['ReportsTo'];
if (CheckLength($dbEntries['Password1']))
{
$query .= ", Password='" . $dbEntries['Password1'] .
"'";
}
$query .= " WHERE EmployeeID = $employeeID";
$db->query($query);
echo '<div align="center">Record Updated</div>';
}
elseif (!count($errors))
{
$showForm = false;
?>

---- C O D E O M I T T E D ----
}
else
{
$dbEntries = $_POST;
}
?>
This file is the same as the ProcessEmployee.php file we saw before with a few important
changes:
1. Instead of assigning values from $_POST to $dbEntries one by one, we simply copy
$_POST into $dbEntries and then loop through the array to pass each element
through dbString(). Notice the use of the & to make $entrya reference to rather
than a copy of the array element.
2. The call to checkPassword() now contains a third parameter to specify whether the
function should return false if the password fields are not filled out. We only want to
check the password length for new entries, not for updates.
3. If the EmployeeID key exists in the $_POST array, then the Edit Employee form has
been submitted and a database query will be executed to update the employee record.
mysqli Prepared Statements
With mysqli it is possible to create prepared statements, which improve performance and
improve security. Prepared statements are essentially templated queries to which you can
bind input and output variables.
To see the results, open the file in your browser passing a city (e.g, London) via the query
string. For example,
http://localhost/Webucator/ClassFiles/ManagingData/Demos/PreparedStatement.php?City=L
ondon
To illustrate, look at the following example.
Code Sample:
ManagingData/Demos/PreparedStatement.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
<!DOCTYPE HTML>
<html>
<head>
<meta charset="UTF-8">
<title>Prepared Statement</title>
</head>
<body>
<?php
$companyID = $_GET['City']; //Try London

@$db = new mysqli('localhost','root','pwdpwd','Northwind');
if (mysqli_connect_errno())
{
echo 'Cannot connect to database: ' . mysqli_connect_error();
}
else
{
$query = 'SELECT CompanyName,ContactName,Phone
FROM Customers WHERE City=?';
$stmt = $db->prepare($query);
$stmt->bind_param('s',$companyID);
$stmt->execute();
$stmt->bind_result($company,$contact,$phone);
?>
<table border="1">
<tr>
<th>Company</th>
<th>Contact</th>
<th>Phone</th>
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
</tr>
<?php
while ($stmt->fetch())
{
echo '<tr>';
echo "<td>$company</td>";
echo "<td>$contact</td>";
echo "<td>$phone</td>";
echo '</tr>';
}
?>
</table>
<?php
$stmt->close();
$db->close();
}
?>
</body>
</html>
Using the object-oriented interface, the process is as follows:
1. A query is created with question marks used as placeholders for parameters (input
variables).
2. A statement is prepared using the prepare() method, which takes a query as an
argument.
3. Parameters can be bound to the statement with the bind_param() method. The first
argument of this method is a string that has one character for each subsequent
argument. The character specifies the data type of that input parameter. For example,
"isd" would specify that the input parameters are an integer, string, and double, in
that order. The only other option is b for blob.
4. The statement is executed with the execute() method.
5. If the query returns results (e.g, SELECT queries), they can be bound to the statement
with the bind_result() method.
6. The fetch() method can be used to fetch rows from the result set.
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 Procedural Description
$db->prepare() mysqli_prepare()
Prepares a SQL statement for
execution.
$stmt- mysqli_stmt_bind_result()
Binds variables to a prepared
Prepare Functions
Object-oriented Procedural Description
>bind_result()
statement results.
$stmt-
>bind_param()
mysqli_stmt_bind_param()
Binds variables to a prepared
statement.
$stmt->execute() mysqli_stmt_execute()
Executes a prepared statement.
$stmt->fetch() mysqli_stmt_fetch()
Fetches results into the bound
variables.
$stmt->close() mysqli_stmt_close()
Closes prepared statement.
PHP Tutorial
MDB2
PEAR supplies a number of open source extensions to PHP including the MDB2 package,
which provides a database abstraction layer, so that the PHP programmer doesn't have to
worry about all the APIs for different databases. The homepage for PEAR is at
http://pear.php.net For information on installing PEAR, visit
http://pear.php.net/manual/en/installation.php.
Lesson Goals
Use the PEAR MDB2 package as a database abstraction layer.
Advantages and Disadvantages of MDB2
MDB2 is a database abstraction layer. Whether or not you decide to use MDB2 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 MDB2 is certainly helpful. If performance
is key, then you may find the extra weight of MDB2 to be prohibitive.
Why use a database abstraction layer?
One big benefit of using a database abstraction layer like MDB2 is portability. MDB2 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, MDB2 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 MDB2
The connection string for connecting to the database with MDB2 is:
Syntax
driver://username:password@host/database
Some of the drivers supported by MDB2 are
mysql
mysqli
mssql
oci8
odbc
pgsql
sqlsrv
querysim
sqlite
To use mysqli to connect to the Northwind database, you would use the following connection
string:
mysqli://username:password@host/Northwind
Code Sample:
MDB2/Demos/EmployeeReport.php
1
2
3
4
5
6
<!DOCTYPE HTML>
<html>
<head>
<meta charset="UTF-8">
<title>Employee Report</title>
</head>
<body>
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
<?php
require_once 'MDB2.php';
$db = MDB2::connect('mysqli://root:pwdpwd@localhost/Northwind');
if (PEAR::isError($db))
{
echo 'Cannot connect to database: ' . $db->getMessage();
}
else
{
$sql = 'SELECT * FROM Employees';
$result = $db->query($sql);
$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(MDB2_FETCHMODE_ASSOC))
{
echo '<tr>';
echo '<td>' . $row['firstname'] . '</td>';
echo '<td>' . $row['lastname'] . '</td>';
echo '<td>' . $row['title'] . '</td>';
echo '<td>' . $row['email'] . '</td>';
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
echo '<td align="right">x' . $row['extension'] . '</td>';
echo '</tr>';
}
?>
</table>
<?php
$result->free();
$db->disconnect();
}
?>
</body>
</html>
As you can see, the MDB2 API is very similar to the mysql object-oriented API. Let's walk
through the code.
1. First, we include the MDB2 library. Notice that we simply use MDB2.php for the path:
require_once 'MDB2.php';
2. This will only work if:
o MDB2.php is in the same directory as EmployeeReport.php. This isn't likely as
MDB2.php itself includes files, which would also have to be in the same directory.
OR...
o The include_path directive in php.ini includes a path to the pear folder containing
MDB2.php.
3. Next, we connect to the database:
$db = MDB2::connect('mysqli://root:pwdpwd@localhost/Northwind');
4. This line of code will create a connection object if the connection is successful or an error
object if it is not. The :: syntax will be covered when we discuss object-oriented PHP
programming, but the crux of it is that the connect() method is a class-level method
rather than an object-level method, so it can be called without first instantiating an object.
5. If this doesn't make sense, don't worry about it. It will be clearer after you've learned about
object-oriented programming.
6. We then use the class-level isError() method to check if $db is an error object, which
would mean that the connection failed. If it did fail, we output an error.
1
2
3
4
if (PEAR::isError($db))
{
echo 'Cannot connect to database: ' . $db->getMessage();
}
7. If the connection succeeded, we run our query:
1
2
3
$sql = 'SELECT * FROM Employees';
$result = $db->query($sql);
$numResults = $result->numRows();
8. And, after writing out our header row, we loop through the query results outputting a row
for each record returned:
1
2
3
4
5
6
7
8
9
while ($row = $result->fetchRow(MDB2_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>';
}
9. The fetchRow() method can take one of several constants to specify how a row is
returned. In this example, we use MDB2_FETCHMODE_ASSOC to get the row as an associative
array. Other options are MDB2_FETCHMODE_ORDERED (the default) and
MDB2_FETCHMODE_OBJECT, which get the row as an indexed array and an object,
respectively.
PHP Tutorial
Authentication with PHP and SQL
In this lesson, you will learn the basic concept of authentication with PHP.
Lesson Goals
Authenticate users with a login form.
A Database-less Login Form
Below is a simple login form that uses a hard-coded username and password.
Code Sample:
Authentication/Demos/SimpleLogin.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
<!DOCTYPE HTML>
<html>
<head>
<meta charset="UTF-8">
<title>Login Page</title>
</head>
<body>
<?php
require 'Includes/Header.php';

$msg='';
$email = '';
if (array_key_exists('LoggingIn',$_POST))
{
$email = $_POST['Email'];
$pw = $_POST['Password'];
if ($email == '[email protected]' && $pw == 'cowboy')
{
echo '<div align="center">Success</div>';
}
else
{
echo '<div align="center">Login Failed</div>';
unset($_POST['LoggingIn']);
}
}

if (!array_key_exists('LoggingIn',$_POST))
{
?>

<div align="center">
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62

<h2>Log in</h2>
<form method="post" action="SimpleLogin.php">
<input type="hidden" name="LoggingIn" value="true">
<table>
<tr>
<td>Email:</td>
<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.php';
?>
</body>
</html>
This page contains an HTML login form, which submits to itself (i.e, the action points to the
same page). A hidden field, LoggingIn, is passed to the server when the user submits the
form. The script checks to see if LoggingIn exists in the $_POST array. If it does, it processes
the form input:
1
2
3
4
5
6
7
8
9
$email = $_POST['Email'];
$pw = $_POST['Password'];
if ($email == '[email protected]' && $pw == 'cowboy')
{
echo '<div align="center">Success</div>';
}
else
{
echo '<div align="center">Login Failed</div>';
unset($_POST['LoggingIn']);
}
10
11
This code simply checks to see if the user's email and password match the hard-coded values
([email protected] and cowboy). If they do, it outputs a "success" message. If they
don't, it outputs a "failed" message and removes LoggingIn from the $_POST array, so that
the form will be displayed again.
PHP Tutorial
Regular Expressions
Regular expressions are used to do sophisticated pattern matching. PHP supports two types of
regular expressions: POSIX and Perl. The Perl style is more powerful and much more
common, so we'll cover these in this class.
Lesson Goals
Understand how regular expressions work.
Use regular expressions for advanced form validation.
What is a Regular Expression
A regular expression is a pattern that specifies a list of characters. In this section, we will
look at how those characters are specified. As we go through this section, we'll test some
regular expression in our browser using our regular expression tester at
RegExp/Demos/Tester.php.
Start and End ( ^ $ )
A caret (^) at the beginning of a regular expression indicates that the string being searched
must start with this pattern.
The pattern ^foo can be found in "food", but not in "barfood".
A dollar sign ($) at the end of a regular expression indicates that the string being searched
must end with this pattern.
The pattern foo$ can be found in "curfoo", but not in "food".
Number of Occurrences ( ? + * {} )
The following symbols affect the number of occurrences of the preceding character: ?, +, *,
and {}.
Or characters if parentheses are used to create subpatterns.
A questionmark (?) indicates that the preceding character should appear zero or one times in
the pattern.
The pattern foo? can be found in "food" and "fod", but not "faod".
A plus sign (+) indicates that the preceding character should appear one or more times in the
pattern.
The pattern fo+ can be found in "fod", "food" and "foood", but not "fd".
A asterisk (*) indicates that the preceding character should appear zero or more times in the
pattern.
The pattern fo*d can be found in "fd", "fod" and "food".
Curly brackets with one parameter ( {n} ) indicate that the preceding character should appear
exactly n times in the pattern.
The pattern fo{3}d can be found in "foood" , but not "food" or "fooood".
Curly brackets with two parameters ( {n1,n2} ) indicate that the preceding character should
appear between n1 and n2 times in the pattern.
The pattern fo{2,4}d can be found in "food","foood" and "fooood", but not "fod" or
"foooood".
Curly brackets with one parameter and an empty second paramenter ( {n,} ) indicate that the
preceding character should appear at least n times in the pattern.
The pattern fo{2,}d can be found in "food" and "foooood", but not "fod".
Common Characters ( . \d \D \w \W \s \S )
A period ( . ) represents any character except a newline.
The pattern fo.d can be found in "food", "foad", "fo9d", and "fo*d".
Backslash-d ( \d ) represents any digit. It is the equivalent of [0-9].
The pattern fo\dd can be found in "fo1d", "fo4d" and "fo0d", but not in "food" or "fodd".
Backslash-D ( \D ) represents any character except a digit. It is the equivalent of [^0-9].
The pattern fo\Dd can be found in "food" and "foad", but not in "fo4d".
Backslash-w ( \w ) represents any word character (letters, digits, and the underscore (_) ).
The pattern fo\wd can be found in "food", "fo_d" and "fo4d", but not in "fo*d".
Backslash-W ( \W ) represents any character except a word character.
The pattern fo\Wd can be found in "fo*d", "fo@d" and "fo.d", but not in "food".
Backslash-s ( \s) represents any whitespace character (e.g, space, tab, newline, etc.).
The pattern fo\sd can be found in "fo d", but not in "food".
Backslash-S ( \S ) represents any character except a whitespace character.
The pattern fo\Sd can be found in "fo*d", "food" and "fo4d", but not in "fo d".
Grouping ( [] )
Square brackets ( [] ) are used to group options. This creates what is referred to as a
"character class".
The pattern f[aeiou]d can be found in "fad" and "fed", but not in "food", "faed" or "fd".
The pattern f[aeiou]{2}d can be found in "faed" and "feod", but not in "fod", "fed" or
"fd".
Negation ( ^ )
When used after the opening square bracket of a character class, the caret ( ^ ) is used for
negation.
The pattern f[^aeiou]d can be found in "fqd" and "f4d", but not in "fad" or "fed".
Subpatterns ( () )
Parentheses ( () ) are used to capture subpatterns.
The pattern f(oo)?d can be found in "food" and "fd", but not in "fod".
Alternatives ( | )
The pipe ( | ) is used to create optional patterns.
The pattern foo$|^bar can be found in "foo" and "bar", but not "foobar".
Escape Character ( \ )
The backslash ( \ ) is used to escape special characters.
The pattern fo\.d can be found in "fo.d", but not in "food" or "fo4d".
Form Validation Functions with Regular
Expressions
Regular expressions can be used to write sophisticated form validation functions. For
example, earlier in the course, we wrote a checkEmail() function that looked like this:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
function checkEmail($email)
{
$email = trim($email);
if (!checkLength($email,6))
{
return false;
}
elseif (!strpos($email,'@'))
{
return false;
}
elseif (!strpos($email,'.'))
{
return false;
}
elseif (strrpos($email,'.') < strpos($email,'@'))
{
return false;
}
return true;
}
We can use a regular expression to make this function both simpler and more powerful:
1
2
3
4
5
function checkEmail($email)
{
$emailPattern = '/^(\w+\.)*\w+@(\w+\.)+[A-Za-z]+$/';
return preg_match($emailPattern,$email));
}
A nice thing about this is that we can use virtually the same function to do client-side
validation with JavaScript:
1
2
3
4
5
function checkEmail(EMAIL)
{
var reEmail = /^(\w+[\-\.])*\w+@(\w+\.)+[A-Za-z]+$/;
return reEmail.test(EMAIL));
}
So, by using regular expressions in this way, you make it easy to create a similar function
library on the client side.
Perl-compatible Regular Expression
Functions
preg_match()
The syntax for preg_match() is as follows.
1 preg_match(pattern, text_to_search);
preg_match() returns 1 if pattern is found in text_to_search and 0 if it is not.
preg_replace()
The syntax for preg_replace() is as follows.
1 preg_replace(pattern, replacement, text_to_search);
preg_replace() replaces all instances of pattern in text_to_search with replacement.
Regular Expression Tester
We have created a simple PHP-based regular expression tester. The code for the tester is
shown below.
Code Sample:
RegExp/Demos/Tester.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
<?php
@$pattern = (get_magic_quotes_gpc()) ? stripslashes($_POST['Pattern']) :
$_POST['Pattern'];
@$textToSearch = (get_magic_quotes_gpc()) ?
stripslashes($_POST['TextToSearch']) : $_POST['TextToSearch'];
?>
<!DOCTYPE HTML>
<html>
<head>
<meta charset="UTF-8">
<title>Regular Expression Tester</title>
<style>
.big {font-family:Verdana; font-size: 14pt; font-weight:bold;
color:darkblue; text-decoration:none; padding: 4px}
.reg:hover {border: 2px solid red; padding: 2px}
</style>

<script>
function usePattern(PATTERN)
{
document.formRE.Pattern.value=PATTERN;
document.getElementById("display").innerHTML="<b>PATTERN: </b>" +
PATTERN;
}
</script>
</head>
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49

<body>
<h2>Regular Expression Tester</h2>
<form name="formRE" method="post">
<table>
<tr>
<td align="right"><span class="big">Text to search:</span></td>
<td><input type="text" name="TextToSearch" value="<?= $textToSearch
?>" size="50" maxlength="50"></td>
</tr>
<tr>
<td align="right"><span class="big">Pattern:</span></td>
<td><input type="text" name="Pattern" size="50" value="<?= $pattern ?>"
maxlength="100"></td>
</tr>
<tr>
<td colspan="2" align="center">Try these patterns:
<a href="javascript:usePattern('/^[a-zA-Z0-9_\\-\\.]+@[a-zA-Z0-
9\\-]+\\.[a-zA-Z0-9\\-\\.]+$/');">Email</a> |
<a href="javascript:usePattern('/^[0-9]{3}[\\- ]?[0-9]{2}[\\-
]?[0-9]{4}$/');">SSN</a> |
<a href="javascript:usePattern('/^\\(?[2-9][0-9]{2}\\)?[\\- ]?[0-
9]{3}[\\- ]?[0-9]{4}$/');">Phone</a>
</td>
</tr>
<tr>
<td colspan="2" align="center" style="font-size:18pt; font-
family:Arial, Helvetica, sans-serif; background: #cccccc;">
<?php
if (empty($pattern))
echo '<span style="color:blue">Let\'s play!</span>';
elseif (preg_match($pattern,$textToSearch))
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
echo '<span style="color:green">Match</span>';
else
echo '<span style="color:red">No Match</span>';
?>
</td>
</tr>
<tr align="center">
<td colspan="2">
<input type="submit" value="Submit">
<input type="reset">
</td>
</tr>

</table>
</form>
<div id="display" style="font-size:18pt; font-family:Courier
New"><b>PATTERN:</b> <?= $pattern ?></div>

</body>
</html>
PHP Tutorial
Session Control and Cookies
In the lesson on authenticaion, we created a login form and learned to authenticate users by
comparing their emails and passwords to records in a database. In this lesson, 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.
Lesson Goals
Maintain sessions to track user visits.
Write and read cookies.
Sessions
A session begins when a visiting client somehow identifies itself to the web server. The web
server assigns the client a unique session id, which the client uses to re-identify itself as it
moves from page to page on the website. Most of the time, these unique ids are stored in
session cookies that expire after the client hasn't interacted with the server for some amount
of time. The amount of time varies depending on the web application. For example, an online
investment site might have very short sessions, so that if a user leaves her computer without
logging out, another user who sits down at the same computer several minutes later cannot
continue with the first user's session.
Configuring Sessions
In PHP, session management is configured in the php.ini file. To have a user's session start as
soon as the user visits the website, the session.auto_start flag must be set to 1.
The session length is also set in the php.ini file with the session.gc_maxlifetime variable.
The default value is 1440 seconds (24 minutes).
Session Functions
The following table shows the most common session functions.
Function Explanation
session_start()
Starts new session if one does not exist. Continues current session if
one exists.
session_unset()
Unsets all session variables.
session_destroy()
Kills session.
Together, the files below illustrate how sessions can be tracked.
Code Sample:
Sessions/Demos/Session1.php
1
2
3
4
5
6
7
8
9
10
11
<?php
//Begin a session and create a session variable in
//the $_SESSION array.
session_start();

$_SESSION['Greeting'] = 'Hello world!';

echo $_SESSION['Greeting'];
?>
<hr>
<a href="Session2.php">Next page</a>
Code Sample:
Sessions/Demos/Session2.php
1
2
3
4
5
6
7
8
9
10
<?php
//Continue session, show that session variable still
//exists and then unset the session variable
session_start();

echo $_SESSION['Greeting'];

unset($_SESSION['Greeting']);
?>
<a href="Session3.php">Next page</a>
Code Sample:
Sessions/Demos/Session3.php
1
2
3
4
5
6
7
8
9
10
<?php
//Continue session, show that session variable no longer
//exists and then kill session.
session_start();

echo $_SESSION['Greeting'];

session_unset();
session_destroy();
?>
The code above illustrates the following points.
Pages that are part of the session should begin with a call to session_start().
Session variables are created in the $_SESSION array.
Session variables are deleted in the same way as other variables - using the unset()
function.
All session variables can be unset with the session_unset() function. This should
be called before calling session_destroy().
Sessions are killed with a call to session_destroy().
Cookies
Cookies are stored in text files that sit on the client machine. Web pages with the right
permissions can read from and write to cookies. They are generally used to track user
information between visits.
In PHP, cookies are set with the setcookie() function, which can take several parameters
including:
The cookie's name (required).
The cookie's value.
The cookie's expiration date (if this isn't set, the cookie will expire when the browser
window is closed).
The directory path on the server that can read the cookie.
The domain name that can read the cookie.
A flag indicating whether the cookie should only be read over https.
The following code will set a cookie that expires in one week.
setcookie('flavor','chocolate chip', time()+60*60*24*7);
There is no deletecookie() function. To delete a cookie, set the expiration date to
sometime in the past, like this.
setcookie('flavor','chocolate chip', time()-10000);
Cookies are set in the HTTP header, so they must be set before any HTML code is passed
back to the browser.
PHP Tutorial
Sending Email with PHP
In this lesson, you will learn how to send emails with PHP using both the built-in mail()
function and the PHPMailer extension.
Lesson Goals
Send emails using PHP's built-in mail() function.
Send email using PHPMailer, a PHP extension with more features than mail().
mail()
PHP has a built-in mail() function that makes it easy to send email.
Mail Parameters
Parameters Description
To The address to send the email to.
Subject The email's subject.
Message The body of the email.
Additional Headers Optional. Additional headers (e.g, From, Reply-To)
Mail Parameters
Parameters Description
Additional
Parameters
Optional. Any additional parameters you may want to send to your mail
server.
Note: when running any script that sends out emails, you will need a mail server and
access credentials. Check with your System Administrator or with your Internet Hosting
Service Provider to get the mail server information.
Code Sample:
Email/Demos/Mail.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
<!DOCTYPE HTML>
<html>
<head>
<meta charset="UTF-8">
<title>Mail()</title>
</head>
<body>
<?php
if (!array_key_exists('Submitted',$_POST))
{
?>
<form method="post" action="Mail.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>
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
<?php
}
else
{
ini_set('SMTP',$_POST['Host']);
$to = $_POST['To'];
$from = 'From: ' . $_POST['From'];
$subject = $_POST['Subject'];
$message = $_POST['Message'];

if(mail($to,$subject,$message,$from))
{
echo "Message Sent";
}
else
{
echo "Message Not Sent";
}
}
?>
</body>
</html>
For this example to work, you will need to have a mail server set up on your server.
The first time a visitor hits the page, he'll be presented with a form. When the user fills out
and submits that form, the mail() function will attempt to send an email to the address the
user entered.
Note that the mail server is set with the ini_set() function, which is used to temporarily
change configuration settings. You can set the default mail server in the php.ini file with the
SMTP setting.
Shortcomings of mail()
The mail() function has many limitations.
No support for SMTP authentication.
Difficult to send HTML-formatted emails.
Difficult to add attachments.
Luckily, there are extensions that do provide these features.
PHPMailer
A very good email extension is PHPMailer, which is available for free at
http://phpmailer.worxware.com. We will use PHPMailer in our examples and exercises. The
following tables show some of the more common methods and properties of PHPMailer.
PHPMailer Methods
Method Description
AddAddress() Adds a "To" address.
AddAttachment() Adds an attachment from a path on the filesystem.
AddBCC() Adds a "bcc" address.
AddCC() Adds a "cc" address.
AddReplyTo() Adds a "Reply-to" address.
IsHTML() Sets message type to HTML.
IsSMTP() Sets Mailer to send message using SMTP.
Send()
Creates message and assigns Mailer. If the message is not sent successfully then
it returns false.
PHPMailer Properties
Property Description
AltBody Sets the text-only body of the message.
PHPMailer Properties
Property Description
Body Sets the Body of the message. This can be either an HTML or text body.
ErrorInfo Holds the most recent mailer error message.
From Sets the From email address for the message.
FromName Sets the From name of the message.
Host Sets the SMTP hosts. All hosts must be separated by semicolons.
Password Sets SMTP password.
SMTPAuth Sets SMTP authentication. Utilizes the Username and Password properties.
Subject Sets the Subject of the message.
Username Sets SMTP username.
WordWrap Sets word wrapping on the body of the message to a given number of characters.
Note: when running any script that sends out emails, you will need a mail server and access
credentials. Check with your System Administrator or with your Internet Hosting Service
Provider to ge the mail server information.
Code Sample:
Email/Demos/PHPMailer.php
1
2
3
4
5
6
7
8
<!DOCTYPE HTML>
<html>
<head>
<meta charset="UTF-8">
<title>PHPMailer</title>
</head>
<body>
<?php
if (!array_key_exists('Submitted',$_POST))
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
{
?>
<form method="post" action="PHPMailer.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.phpmailer.php");
$to = $_POST['To'];
$from = $_POST['From'];
$fromName = $_POST['FromName'];
$subject = $_POST['Subject'];
$message = $_POST['Message'];
$host = $_POST['Host'];

if (array_key_exists('HTML',$_POST))
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
{
$html = true;
}
else
{
$html = false;
}

$mail = new PHPMailer();

$mail->IsSMTP(); // send via SMTP
$mail->Host = $host; //SMTP server

if (strlen($_POST['Username']))
{
$mail->SMTPAuth=true;
$mail->Username=$_POST['Username'];
$mail->Password=$_POST['Password'];
}
else
{
$mail->SMTPAuth=false;
}

$mail->From = $from;
$mail->FromName = $fromName;
$mail->AddAddress($to);
$mail->AddReplyTo($from);

63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
$mail->WordWrap = 50; // set word wrap
$mail->IsHTML($html);

$mail->Subject = $subject;
$mail->Body = $message;

if($mail->Send())
{
echo "Message Sent";
}
else
{
echo "Message Not Sent<br>";
echo "Mailer Error: " . $mail->ErrorInfo;
}
}
?>
</body>
</html>
As you can see, PHPMailer comes with a full set of intuitive methods and properties that
make sending emails very easy.
PEAR also provides an email package at PEAR::Mail_Mime. It has similar functionality to
PHPMailer.
PHP Tutorial
File System Management
Most Web applications use databases to store large amounts of data. However, in some cases,
it will be necessary to store data in or access data from files.
Lesson Goals
Read from files on the server.
Write to files on the server.
Upload files to the server.
Obtain information about files on the server.
Access and work with directories on the server.
Opening a File
fopen()
Syntax
fopen (path_to_file, file_mode)
path_to_file can either be a relative or an absolute path.
File Modes
File
Mode
Description
r
open for reading
w
open for writing (erases existing content); creates new file if one doesn't exist
a
open for appending to end of content; creates new file if one doesn't exist
x
create and open for writing (new in PHP 4.3.2); fails and returns false if file
already exists
r+
open for reading and writing (erases existing content when file is written to)
w+
open for writing and reading (erases existing content on opening or creates new file
if one doesn't exist
a+
open for appending and writing; creates new file if one doesn't exist
x+
create and open for writing and reading (new in PHP 4.3.2); fails and returns false
if file already exists
File Permissions
Files that do no have the appropriate permissions settings will fail to open. In this case, the
fopen() function will return false and a warning will be given. Use conditional processing as
shown below to handle this situation.
1
2
3
4
5
6
7
8
9
$myFile = @fopen('MyFile.txt','a');
if (!$myFile)
{
echo '<b>Sorry, but the file cannot be opened.</b>';
}
else
{
// code for processing file
}
The @ symbol in front of first line of code is used to suppress errors. Any errors can then be
handled more gracefully.
Reading from a File
Opening a file for reading involves three steps:
1. Open the file.
2. Read the file.
3. Close the file.
fgets()
fgets() is used to read a file one line at a time. It requires one argument: the resource or
"handle" for the file and accepts a second argument: the length of the line. It will continue
reading the line until the length - 1 have been read or it reaches the end of the line or the end
of the file. If the second argument is not included, it will continue reading until it reaches the
end of the line.
Examine the file shown below.
Code Sample:
Files/Demos/Employees.txt
1
2
3
4
5
6
7
8
9
Nancy Davolio Sales Representative [email protected]
Andrew Fuller Vice President, Sales [email protected]
Janet Leverling Sales Representative [email protected]
Margaret Peacock Sales Representative [email protected]
Steven Buchanan Sales Manager [email protected]
Michael Suyama Sales Representative [email protected]
Robert King Sales Representative [email protected]
Laura Callahan Inside Sales Coordinator [email protected]
Anne Dodsworth Sales Representative [email protected]
Employees.txt is a tab-delimited text file. Each line is formatted as follows:
FirstName\tLastName\tTitle\tEmail\n
The file is divided into "columns" using tabs (\t) and each "row" is separated by a newline
character (\n). The code below opens Employees.txt, reads and displays each line, and closes
the file.
Code Sample:
Files/Demos/Employees.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
<!DOCTYPE HTML>
<html>
<head>
<meta charset="UTF-8">
<title>Employees</title>
</head>
<body>
<h1>Employees</h1>
<?php
$myFile = @fopen("Employees.txt", 'r');

if (!$myFile)
{
echo '<p>Cannot open file.';
}
else
{
while (!feof($myFile))
{
$employee = fgets($myFile, 999);
echo $employee.'<br>';
}
fclose($myFile);
}
?>
</body>
</html>
Other options for reading from files
Function Description
fgetss()
Like fgets() but it strips out HTML and PHP tags.
fgetcsv()
Like fgets() but it splits the file on a specified delimiter rather than a newline
character.
readfile(
)
Opens a file, sends its contents to the browser, and closes the file.
file()
Opens a file, splits it into an array on newline characters, and closes the file.
Writing to a File
Opening a file for writing involves three steps:
1. Open the file.
2. Write to the file.
3. Close the file.
fwrite()
Syntax
fwrite(file_pointer,output_string)
The output_string is the text to write to the file. See the following example of writing to a
file.
1
2
3
4
$outputString='text to write';
$myFile = @fopen('Employees.txt', 'a');
fwrite($myFile, $outputString);
fclose($myFile);
File Locking
flock()
flock() is used to lock a file so that two or more people do not get access to it at the same
time. This helps protect the file from being corrupted. flock() takes two arguments: a file
handler and a lock type. flock() does not work with NFS or other networked file systems or
with such as FAT that does not support file locking.
Lock
Type
Explanation
LOCK_SH
Reading lock. Others can read file.
LOCK_EX
Exclusive lock. The file cannot be opened by others.
LOCK_UN
Unlocks file.
LOCK_NB
If a file is already locked by another user, flock() waits to get a lock. LOCK_NB
tells it not to wait.
The code below shows how we should change Files/Solutions/AddEntry.php to protect
Employees.txt from being corrupted.
Code Sample:
Files/Demos/Locking.php
1
2
3
---- C O D E O M I T T E D ----
flock($myFile, LOCK_EX);
fwrite($myFile,$outputString);
4
5
6
flock($myFile, LOCK_UN);
fclose($myFile);
---- C O D E O M I T T E D ----
Uploading Files via an HTML Form
In order to upload files via an HTML form, the form tag's method must be set to "post" and
the enctype must be set to "multipart/form-data" as shown below.
For file uploads to wrok, the file_uploads flag in php.ini must be turned on.
Syntax
1
<form method="post" enctype="multipart/form-data">
The following example demonstrates how to safely allow the user to upload a file to the
server.
Code Sample:
Files/Demos/FileUpload.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
<!DOCTYPE HTML>
<html>
<head>
<meta charset="UTF-8">
<title>Resume Upload</title>
</head>
<body style="text-align:center">
<?php
if (!array_key_exists('Submitted',$_POST)) {
?>
<h2>Resume Upload Form</h2>
<form method="post" enctype="multipart/form-data">
<input type="hidden" name="Submitted" value="true">
<table border="1">
<tr>
<td>First Name</td>
<td><input type="text" name="FirstName" size="20"></td>
</tr>
<tr>
<td>Last Name</td>
<td><input type="text" name="LastName" size="20"></td>
</tr>
<tr>
<td>Resume</td>
<td><input type="file" name="Resume"></td>
</tr>
<tr>
<td colspan="2" align="center"><input type="submit"
value="Upload"></td>
</tr>
</table>
</form>
<?php
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
} else {
//process the form
$resumeFile = $_FILES['Resume']['tmp_name'];
$fileSize = $_FILES['Resume']['size'];
$fileType = $_FILES['Resume']['type'];
$fileError = $_FILES['Resume']['error'];

$resumeName=$_POST['FirstName'] . '_' .
$_POST['LastName'] . '_Resume.txt';
if ($fileError)
{
echo "We could not upload the file:<br>$fileError";
endPage();
}
elseif ($fileType != 'text/plain')
{
echo "You have attempted to upload a file of type: $fileType.
<br>Only text files allowed.";
endPage();
}

$fileSavePath = 'Resumes/' . $resumeName;
if (is_uploaded_file($resumeFile))
{
if (!move_uploaded_file($resumeFile,$fileSavePath))
{
echo 'Could not save file.';
endPage();
}
}
else
{
//This case happens if somehow the file
//we are working with was already on the server.
//It's to stop hackers.
echo 'Hey, what is going on here?
Are you being bad?';
endPage();
}
$resume=makeFileSafe($fileSavePath);
?>
<h2>Thanks!</h2>
<b>We got your resume.</b><hr>
<form>
<textarea cols="60" rows="20"><?echo $resume?></textarea>
</form>
</p>
<?php
}

function endPage()
{
echo '</body></html>';
exit;
}

function makeFileSafe($filePath)
{
$fP = @fopen($filePath,'r+');
if (!$fP)
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
{
return "Could not read file";
}
$contents = fread($fP,filesize($filePath));
$contents = strip_tags($contents);
rewind($fP);
fwrite($fP,$contents);
fclose($fP);
return $contents;
}
?>
</body>
</html>
The first thing to notice about this page is that it submits to itself. The first time it is loaded, it
will show the form. When the form is submitted, it will attempt to upload and save the user's
resume.
1. The form also has an input field of type file that is used to browse for the file to
upload.
2. When the form is submitted, the script assigns values to short named variables.
3. The next block of code is the if-elseif-elseif statement, which checks for errors.
If it finds any, it displays an appropriate message and calls the endPage() user
function, which just closes the HTML page.
4. The next piece of code attempts to upload the file:
1
2
3
4
5
6
7
8
9
if (is_uploaded_file($resumeFile))
{
if (!move_uploaded_file($resumeFile,$fileSavePath))
{
echo 'Could not save file.';
endPage();
}
}
else
{
//This case happens if somehow the file
10
11
12
13
14
15
16
17
//we are working with was already on the server.
//It's to stop hackers.
echo 'Hey, what is going on here?
Are you being bad?';
endPage();
}
5. 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
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
<!DOCTYPE HTML>
<html>
<head>
<meta charset="UTF-8">
<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>
30
31
32
33
The functions used in this script are described in the following table.
Function Description
basename()
Strips off the path and returns the file name.
fileatime()
Returns the last accessed time of the file.
filemtime()
Returns the last modified time of the file.
filetype()
Returns the type of file (e.g, file or dir).
filesize()
Returns the size of the file in bytes.
is_dir()
Returns true if the passed value is a directory, false if it isn't.
is_file()
Returns true if the passed value is a file, false if it isn't.
is_readable()
Returns true if the file is readable, false if it isn't.
is_writable()
Returns true if the file is writable, false if it isn't.
More File Functions
A few more file functions are shown below:
Function Description
file_exists(path_to_file) Checks to see if a file exists.
filesize(path_to_file) Returns the size of file in bytes.
unlink(path_to_file) Deletes the file.
copy()
Copies a file. Takes two arguments: the path to the source file
and the destination to copy the source file to.
rename()
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.
Directory Functions
The following table shows some of the more common directory functions.
Function 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.

You might also like