Вы находитесь на странице: 1из 245

PHP PROGRAMMING

Lecture #1

Introduction to PHP

Introduction
to PHP

PHP is a widely-used Open Source, general-purpose ,scripting language that is especially suited for
Web development and can be embedded into HTML. According to the php.net site, the acronym
PHP is short for PHP: Hypertext Preprocessor. Its syntax draws upon C, Java, and Perl, and is
easy to learn. The main goal of the language is to allow web developers to write dynamically
generated web pages quickly, but you can do much more with PHP.
You can learn this language by understanding how its primary functions work, how it interacts with
HTML, and how its nature of being a server-side scripting language differs from a client-side
language, such as JavaScript.
PHP code must be executed on the server. Only the output it generates is delivered to client
browser. Consider the following example.
<html>
<?php echo "<h1>Welcome to CIS246!</h1>";
</html>

A PHP script similar to the one above will not run on a client-side browser. It must be execute on a
Web server with the support of a PHP interpreter. The server, after execution, generates the string
output, as shown below, and sends it along with the rest of HTML tags to the client browser.
<h1>Welcome to CIS246!</h1>

What the client receives is a completed HTML code looks like:


<html><h1>Welcome to CIS246!</h1></html>

PHP supports all major operating systems, including Linux/ Unix, Microsoft Windows, Mac OS X,
and others. PHP has also support most of the web servers including Apache, Microsoft Internet
Information Server, Personal Web Server, Netscape, iPlanet servers, and many others.
Basically a web server, such as Apache, needs only to activate support for PHP and that all files
ending in .php are recognized as PHP code. To support a PHP-based data-driven site, you will most
likely want to create and use a database with database languages such as MySQL.
The php.net
site

The http://www.php.net site is the primary web site for PHP language and support. This site
is where you can download the latest version of PHP along with manuals and other reference
documents. As of September 2010, the latest version is PHP 5.3.3. For Windows users, be sure to
download the Windows Binaries at http://windows.php.net/download/.

This site has a search engine. You can consider using it as a reference library. For example, to
search for date-related function, enter the keyword date in the textbox.
PHP

The search will return a page from that PHP manual describing the date function in PHP.

How does a
PHP script
look like?

PHP scripts are text files that can be created by any text editor, such as Notepad. It frequently
includes HTML tags. But instead of the .htm or .html extension, the files are given the .php
extension. Within the file, PHP code is contained in PHP tags.
Consider at a very simple PHP script that displays Welcome to CIS246! in the browser window.
The script is a text-only file, called example1.php, and the file is uploaded to the server.
<html>
<body>
<?php
echo "Welcome to CIS246!";
?>
</body>
</html>

This example is a simple but functional PHP script. It uses only an echo command to output a
string. Of course, PHP scripts used incommercial web sites will never be so simple. However, this
code gives you a chance to understand how PHP scripts work on the server side.
The PHP-enabled server reads the following HTML embedded PHP code and then executes the
echo command.
<?php
echo "Welcome to CIS246!";
?>

The generated string Welcome to CIS246! is then inserted between HTML <body> and
</body> tags, as shown below, and then only the following HTML code is delivered to the client
browser.
<html>
<body>
Welcome to CIS246!
</body>
</html>

All of the PHP codes are processed and stripped from the page. The only thing returned to the client
from the Web server is pure HTML output. The source code of the above example tells us the
following:
Because the page is rendered on the server before it hits the browser, the browser does not see
the PHP code.
The entire <?php ?> tag is replaced by the HTML output from the PHP code.
Every PHP statement ends with a semi-colon, ;
PHP

PHP is an excellent tool for writing dynamic web pages. Non-technical users can easily learn a few
handy tricks to make their web pages easier to manage and more useful.
Static vs.
dynamic
PHP code

Technically speaking, all pages that contain PHP code will end in the extension .php. There are
basically two ways to create a PHP page. All PHP pages are variations on these two methods:
Method 1: Static with PHP Blurbs (HTML with embedded PHP code)
<HTML>
<BODY>
<?php
SOME PHP CODE HERE!
?>
</BODY>
</HTML>

Method 2: Dynamic by Default (PHP code with embedded HTML generated code)
<?php
PHP CODE
?>

There are some cases where you MUST use method 2, but for most of our work, you will be able to
use whichever method you prefer.
Beginning
and Ending a
Block of
PHP
Statements

When writing PHP, you need to inform the PHP engine that you want it to execute your PHP
commands. If you don't do this, the code you write will be mistaken for HTML code and will be
output to the browser. You can do this with special tags such as, <?php ?>, <? ?>, or
<script></script> that mark the beginning and end of all PHP code blocks.
Tag Style
Standard
Short
Script

Beginning

Closing

<?php
<?
<script language="php">

?>
?>
</script>

For example, the following three lines yield the same results.
<?php echo "Welcome!"; ?>
<? echo "Welcome!"; ?>
<script language="php"> echo "Welcome!"; </script>

PHP uses semicolon ; as the statement delimiter.


Two basic
output
functions

The two basic PHP output functions are print and echo. These functions are used as follows:
print "Hello World";
echo "Hello World";

Now, you might be wondering when to use each of these two functions if they're are similar. Well,
there are really two differences.
Print will place a "newline character" (\n) at the end of each print statement so that you don't
manually have to print out a new line. With echo, you really should use:
echo "Hello World\n";

PHP

The \n is the representation of a newline. The PHP echo function can also accept multiple
arguments, as in:
echo "Hello ", "World!", "\n";

You can use either a single quote (') or a double quote (") unless what you are trying to print
contains a variable or a special character (like \n). More details on that in later lecture.
Commenting
your PHP
code

Commenting your code is a good habit to practice. Entering comments in HTML documents helps
you (and others who might have to edit your document later) keep track of what's going on in large
amounts of code. Comments also allow you to write notes to yourself during the development
process, or to comment out parts of code when you are testing your scripts, in order to keep code
from being executed.
HTML comments are ignored by the browser and are contained within <!-- and --> tags. For
example, the following comment reminds you that the next bit of HTML code contains a logo
graphic:
<!-- logo graphic goes here -->

PHP uses comments, too, which are ignored by the PHP parser (interpreter). PHP comments are
usually preceded by a double slash, like this:
// this is a comment in PHP code

However, you can also use the following type of comment syntax for multiple-line comments:
/* Put a multiple-line comment here */
# using Linux/Unix shell type of comment

Formatting
PHP outputs
using HTML
tags

Essentially, PHP is an inline scripting language developed for use with HTML. What this means is
that PHP and HTML can be intertwined with each other in a webpage. This means that not all of the
webpage must be generated by the PHP. You can use HTML formatting tags to format output
generated by PHP. For example,
<html>
<b><?php echo "Learning without thinking "; ?></b>
is <i><?php echo "not good"; ?></i>
for <u><?php echo "you"; ?></u>
</html>

The output will be:


Learning without thinking is not good for you

You can also include the formatting HTML tags inside the double quotes of the PHP echo
command. For example,
<html>
<?php echo "<b>Learning without thinking </b>"; ?>
is <?php echo "<i>not good</i> "; ?>
for <?php echo "<u>you</u>"; ?>
</html>

Or, to its simplest way, use:


<html>
<?php
echo "<b>Learning without thinking </b>

PHP

is <i>not good</i>
for <u>you</u>";
?>
</html>

Installing
PHP

The Windows PHP installer is built using Microsofts MSI technology, so its file name has an
extension of .msi (e.g.: php-5.3.0-nts-Win32-VC9-x86.msi). After downloading the PHP
installer, run the MSI installer and follow the instructions provided by the installation wizard. It will
install and configure PHP. There is a Manual Installation Steps guide that will help manually
install and configure PHP with a web server installed in a Microsoft Windows operating system. It
is available at http://www.php.net/manual/en/install.windows.manual.php.
For Mac OS X users, there are notes and hints specific to installing PHP on Mac OS X. Details are
available at http://www.php.net/manual/en/install.macosx.php.
For Linux users, simply refer to the manual provided by the distributer. For Fedora users, use the
following to install Apache (httpd), PHP, MySQL (server and client), and the component that allows
PHP to talk to MySQL using the root account.
yum -y install httpd php mysql mysql-server php-mysql

Be a certified
PHP
programmer

Have you heard about the Zend Certified Engineer (ZCE) exam? The zend.com web site is a
resource to help you pass your Zend PHP 5 Certification. The certification sets industry standards
for PHP that can help you stand out from the competition. Visit
http://www.zend.com/en/services/certification/ for more details.

Zends also publishs the Zend PHP 5 Certification Guide. Detailed information is available at
http://shop.zend.com/en/zend-php5-certification-guide-pdf.html. You can

consider becoming a Zend Certified PHP Engineer, which is definitely an eye-catching criterion to
your future employers.
Review of
HTML

PHP relies heavily on HTML. If you feel you dont have a strong background in HTML, please
review the HTML tutorial lessons provided by World Wide Web Consortium (W3C). The URL is
http://www.w3.org/html/ .

Review
Questions

1. What does PHP stand for?


A. Private Home Page
B. Personal Home Page
C. PHP: Hypertext Preprocessor
D. Personal Hypertext Processor
2. PHP server scripts are surrounded by which delimiters?
A. <?php>...</?>
B. <?php?>
C. <script>...</script>
D. <&>...</&>

PHP

3. How do you write "Hello World" in PHP?


A. echo "Hello World";
B. Document.Write("Hello World");
C. "Hello World";
D. Console.Write("Hello world");
4. All variables in PHP start with which symbol?
A. $
B. !
C. &
D. #
5. What is the correct way to end a PHP statement?
A. .
B. ;
C. New line
D. </php>
6. What is a correct way to add a comment in PHP?
A. *\..\*
B. /**/
C. <!---->
D. <comment></comment>
7. Which is the primary Web site for PHP language and supports?
A. http://www.php.com
B. http://www.php.gov
C. http://www.php.net
D. http://www.php.org
8. Which PHP code can yield the following output from a PHP file?
Welcome to CIS246!

A. <?php echo <i>"Welcome to CIS246!"</i>; ?>


B. <?php <i>"Welcome to CIS246!"</i>; ?>
C. <?php echo_i("Welcome to CIS246!"); ?>
D. <i><?php echo "Welcome to CIS246!"; ?></i>
9. What does the client browser receive after the PHP server executes the following PHP script?
<html></body><?php echo "CIS246!"; ?></body></html>

A. <html></body><?php echo "CIS246!"; ?></body></html>


B. <html></body>echo "CIS246!"; </body></html>
C. <html></body>"CIS246!"</body></html>
D. <html></body>CIS246!</body></html>
10. Which of the following would be a Windows PHP installer for Windows operating system?
A. php-5.3.0-nts-Win32-VC9-x86.ins
B. php-5.3.0-nts-Win32-VC9-x86.com
C. php-5.3.0-nts-Win32-VC9-x86.php
D. php-5.3.0-nts-Win32-VC9-x86.msi

PHP

Lab #1

Introduction to PHP

Preparation #1: Build a testing Web Server


1. Use Internet Explorer to visit http://www.apachefriends.org/en/xampp-windows.html and download the
latest installer of XAMPP for Windows. As of the time this lecture is written, the latest version is 1.8.0.
2. Launch the installer file (e.g. xampp-win32-1.8.0-VC9-installer.exe).

3.

Ignore the following message by clicking OK.

4.

In the following initialization window, click Next.

5.

Be sure to browse to and choose the USB thumb drive (e.g. F:\) before clicking Next in the following window.
Set the Destination Folder to X:\xampp (where X: is the drive name).

6.

In the SERVICE SECTION, check Apache, MySQL, and FileZilla as services. Click Install.

PHP

7.

Wait till the installation completes.

8.

You may see the following message. Click OK.

Preparation #2: Running the server and create default database


Notice: Each time before you using XAMPP, you may have to run the X:\xampp\setup_xampp.bat file (where X:
is the drive letter assigned by Windows) because the drive letter of USB is not always the same.
1.

Find the setup_xampp.bat file from the xampp directory of the USB drive and then execute it. You should
see:
######################################################################
# ApacheFriends XAMPP setup win32 Version
#
#--------------------------------------------------------------------#
# Copyright (C) 2002-2012 Apachefriends 1.8.0
#
#--------------------------------------------------------------------#
# Authors: Kay Vogelgesang (kvo@apachefriends.org)
#
#
Carsten Wiedmann (webmaster@wiedmann-online.de)
#
######################################################################
Do you want to refresh the XAMPP installation?
1) Refresh now!
x) Exit

2.

Press 1 and then [Enter]. If re-configuration succeeds, you should see the following message.
XAMPP is refreshing now...
Refreshing all paths in config files...
Configure XAMPP with awk for Windows_NT

PHP

###### Have fun with ApacheFriends XAMPP! ######


Press any key to continue ...

3.

The re-configuration is not necessary if the following message appears.


Sorry, but ... nothing to do!

4.
5.

Execute the xampp-control.exe file (in the X:\xampp directory) to launch the XAMPP Control Panel.
Click the Start buttons of Apche. Read the solution for Port 80 or 443 already in use if you encounter one or
both problems; otherwise proceed to Learning Activity #1.
Without error

With error

Solution for Port 80 or 443 already in use (Skip this section if you do not have this problem)
1. Use Notepad to open the X:\xampp\apache\conf\httpd.conf file. You can simply click the Config button next
to Apache to select the file and open it.
2. Search for words Listen 80 and change into Listen 81 as shown below.

3.

Search for words ServerName localhost:80 and change into ServerName localhost:81

4.
5.

Save and close the file.


Use Notepad to open the X:\xampp\apache\conf\extra\httpd-ssl.conf file.

PHP

6.

look for words Listen 443 and change into Listen 4499

7.
8.
9.
10.

Search for words <VirtualHost _default_:443> and change into <VirtualHost _default_:4499>
Search for words ServerName localhost:443 and change into ServerName localhost:4499
Save and close the file.
Re-start the XAMPP control panel. You may have to run the apache_start.bat file to properly start Apache.
(Note: With this modification, if you wish to access localhost, the URL should be http://localhost:81/. )

Learning Activity #1: Your first PHP-enabled web page (embedded onto an HTML code)
1. Locate the X:\xampp\htdocs directory (where X: is the USB thumb drive or hard drive) and create a new
subdirectory named myphp. Make sure the path is X:\xampp\htdocs\myphp.
2. In the X:\xampp\htdocs\myphp directory, use any generic text editor, such as Windows Notepad, to create a
file named lab1_1.php with the following content:
<html>
<body>Using PHP as part of HTML content:<br />
<?php echo "Welcome to CIS246!"; ?>
</body>
</html>

3.

Use a Web browser to visit http://localhost/myphp/lab1_1.php (where localhost is your computer), you
should see the following window. Notice that you need to use http://localhost:81/myphp/lab1_1.php if you
modified the port number.

4.

Capture a screen shot similar to the above figure and paste it to a Word document named lab1.doc (or
lab1.docx).

Learning Activity #2: Your second PHP script (not embedded onto HTML)
1. In the X:\xampp\htdocs\myphp directory, use Notepad to create a new file named lab1_2.php with the
following contents:
<?php
echo "Welcome to CIS246!";
echo "<h2>PHP can generate HTML output, too!</h2>";
?>

2.

Use a Web browser to visit http://localhost/myphp/lab1_2.php, you should see the following window.

PHP

10

3.

Capture a screen shot similar to the above figure and paste it to a Word document named lab1.doc (or
lab1.docx).

Learning Activity #3: Basic PHP Start and End tags


1. In the X:\xampp\htdocs\myphp directory, use Notepad to create a new file named lab1_3.php with the
following contents:
<html>
<?php echo "Display the word 'Welcome' using '&lt;?php ... &gt;'!"; ?><br>
<? echo "Display the word 'Welcome' using '&lt;? ... &gt;'!"; ?><br>
<script language="php"> echo "Display the word 'Welcome' using '&lt;script&gt;'!";
</script>
</html>

2.

Use a Web browser to visit http://localhost/myphp/lab1_3.php, you should see the following window.

3.

Capture a screen shot similar to the above figure and paste it to a Word document named lab1.doc (or
lab1.docx).

Learning Activity #4: Commenting your PHP code


1. In the X:\xampp\htdocs\myphp directory, use Notepad to create a new file named lab1_4.php with the
following contents:
<html>
<body>
<!-- This line is an HTML comment -->
<?php
//This line is a single line PHP comment.
/*This is a multiple-line comment. Line 1
Line 2
Line 3 */
# This line is a Linux/Unix shell comment
echo "Do you see any of the comment?";
?>
</body>
</html>

2.

Use a Web browser to visit http://localhost/myphp/lab1_3.php, you should see the following window.

PHP

11

3.

Capture a screen shot similar to the above figure and paste it to a Word document named lab1.doc (or
lab1.docx).

Learning Activity #5: Using HTML tag to format PHP output


1. In the X:\xampp\htdocs\myphp directory, use Notepad to create a new file named lab1_5.php with the
following contents:
<html>
<body bgcolor="yellow">
<b><?php echo "PHP Programming!" ?></b><br>
<u><?php echo "PHP Programming!" ?></u><br>
<i><?php echo "PHP Programming!" ?></i><br>
<s><?php echo "PHP Programming!" ?></s><br>
<h1><?php echo "PHP Programming!" ?></h1><br>
<pre><?php echo "PHP Programming!" ?></pre><br>
<center><?php echo "PHP Programming!" ?></center><br>
</body></html>

2.

Use a Web browser to visit http://localhost/myphp/lab1_3.php, you should see the following window.

3.

Capture a screen shot similar to the above figure and paste it to a Word document named lab1.doc (or
lab1.docx).

Submitting the lab


1. Create a .zip file named lab1.zip containing:
Lab1_1.php
Lab1_2.php
Lab1_3.php
Lab1_4.php
Lab1_5.php
Lab1.doc (or .docx and make sure this file contains all the five screen shots)
2.

Upload the zipped file as response to question 11 or Assignment 1 (in Blackboard).

PHP

12

Lecture #2:

PHP Variables, Data Types, and Expressions

Definition
of data type

Human languages, such as English, use combinations of character to represent data. In English,
characters include alpha characters (lowercase and uppercase), numerals (0, 1, 2, .., 9), and symbols
($,#,*,&..). For example:
Jennifer represents a girls first name, and it is a combination of alphabets.
714-852-9634 is a phone number, and it is a combination of numerals and symbol (-).
D009865471 is a student ID, and it is a combination of alphabet and numerals
Different data can use different combinations of alpha characters, numerals, and symbols; therefore,
a data type is set of data with values having predefined characteristics and format. A data type is a
specification that assures the use of a specific set of values.
Usually a limited number of data types are built into a programming language. The language usually
specifies the range of values for a given data type, how the computer processes the values, and how
they are stored. In other words, the data type defines how computers should process a given variable
( of that data type).

What is a
variable?

In programming languages, a variable is a language object that may hold different values for a period
of time. The value of a variable is usually restricted to a certain data type, such as an integer or
floating-point number.
A variable can be thought of as a programming construct used to store both numeric and nonnumeric data.In some cases, the contents of a variable can be changed during program execution. A
variable needs a name to be used to represent a data item whose value can be changed while the
program is running.
Variables in PHP are represented by the dollar sign prefix followed by the name of the variable. The
variable name is case-sensitive. For example:
$name;
$num;

Usually, the value of a given variable is provided by the user. For example, you enter your age to the
text box and then click Go. Your age will be assigned to a variable as value and is later retrieved and
inserted to the next sentence. You can keep on entering different numbers. See the example PHP
code below.
<?php
$age = $_POST["age"];
?>
.......
<form action="test.php" method="post">
<input type="text" name="age">
.......

The above PHP example declares a variable with a valid name (e.g., $age) without assigning initial
value (meaning it has a null value). The $age = $_POST["age"]; line will accept whatever
value the user assigns to the $age through a form. When the user enters a value (e.g., 19), the user
indeed assigns a value to the variable dynamically.
PHP
Expressions

PHP expressions are the building blocks of a PHP code. In PHP, almost any code you write is an
expression. The PHP manual defines a PHP expression as anything that has a value.
The most basic forms of expressions are constants and variables. When you type $a = 5, you assign

PHP

13

5 to the variable, $a. In other words $a = 5 is an expression that the variable $a has the value of 5.
After this assignment, if you wrote $b = $a, you technically express your wish of $b = 5.
Some expressions can be considered as statements. In this case, a statement has the form of
expression;

namely, an expression followed by a semicolon. The following example is a expression and a valid
PHP statement.
$b = $a = 5;

Given an expression, $a = 5. There are two objects involved, the value of the integer 5 and the
variable $a which is being assigned with 5. It simply means that $a = 5. Regardless of what it does, it
is an expression that $a is given the value 5. Thus, writing something like $b = $a = 5; or $b
= ($a = 5); is equivalent to writing two statements: $a = 5; and $b = 5; (a semicolon
marks the end of a statement). Since assignments are parsed in a right to left order, you need to write
$b = $a = 5; (or $a = $b = 5;).
Concept of
using
escaped
sequence

PHP reserves many characters to help processing values held by variables, such as single quote ('),
double quote ('), dollar sign ($), and others. In other words, such reserved characters are not treated
as string literals as in plain English.
Sometimes it is necessary to display special PHP reserved characters as text. In this case, you will
then need to escape the character with a backslash (\). PHP uses the backslash (\) character to
restore and/or redefine characters that otherwise have a special PHP meaning, such as the newline
backslash itself (\n), or the quote character. The restoration/redefinition is known as a "escape
sequence ".
In many languages, escape sequences are used to format values of variables.
Table: Common Escaped characters
Example

Escape
Sequence

Output

\n
\r
\t
\\
\$
\"

break a line
carriage return (equivalent to the [Enter] key)
equivalent to the [Tab] key
display the backslash sign
display the dollar sign
Print a double quote within a string

echo
echo
echo
echo
echo
echo

"Hello
"Hello
"Hello
"Hello
"It is
"He is

World!\n";
World!\r";
\t World!";
\\ World!";
\$150.00";
an \"apple\".";

For example, review the following PHP code:


<?php
echo "A
echo "A
echo "A
echo "A
echo "A
?>

newline starts here \n";


carriage return is \r";
tab is \t.";
dollar sign is \$";
double-quote is \"";

The output should be:


A newline starts here
A carriage return is
A tab is
.A dollar sign is $A double-quote is "

PHP

14

Important Note!
There is a critical problem with using an escaped sequence with web browser--the web browser will
simply ignores blank spaces. And that explains why you did not get the above results when you test
them with web browser. You can use the "View Source" function of the browser to view the correct
output.
Basic PHP
data types

PHP supports a number of different data types. The common ones are integers, floating point
numbers, strings, and arrays. In many languages, it's essential to specify the variable type before
using it. For example, a variable may need to be specified as type integer or type array. A list of
some of the PHP data types and their definitions are:
integer: An integer is a plain whole number like 35, -80, 1527 or 1. They cannot have fractional
part.
floating-point: A floating-point number is typically a fractional number such as 18.5 or
3.141592653589. Floating point numbers may be specified using either decimal or scientific
notation.
string: A string is a sequence of characters, like hello world or abracadabra. String values
may be enclosed in either double quotes ( and ) or single quotes( and ). A blank space inside
the quotes is also considered a character.
boolean: A Boolean variable simply specifies a true or false value.
array: An array is a collection of items that have something in common. A detailed discussion is
given in a later lecture.
Variables in PHP are represented by a dollar sign ($) followed by the name of the variable. For
example, $popeye, $one and $INCOME are all valid PHP variable names. The variable name is
case-sensitive.
To assign a value to a variable, you use the assignment operator, the "=" sign. For example, review
the following PHP code:
<?php
$myvar = "Jennifer";
$Myvar = "Lopez";
echo "$Myvar, $myvar";
?>

The output will be:


Lopez, Jennifer

Both $myvar and $Myvar represent two different variables. The "=" sign is the assignment sign.
$myvar is assigned a value "Jennifer", while $Myvar is assigned another value "Lopez". The echo
command displays both values to the screen. The value being assigned need not always be fixed; it
could also be another variable, an expression, or even an expression involving other variables. For
example:
<?php
$dog_age=10;
$human_age = $dog_age * 7;
echo "Your dog is $human_age years old in human age.";
?>

A variable $dog_age is declared and assigned a value 10. The value of $dog_age variable is then
multiplied by 7, giving a value of 70, as the value of the $human_age variable.
The echo command display the value of $human_age, and the output will be:
Your dog is 70 years old in human age.

PHP

15

Interestingly enough, you can also perform more than one assignment at a time. Consider the
following example, which simultaneously assigns three variables to the same value:
<?php
$price1 = $price2 = $price = 15;
?>

Boolean
Boolean variables are commonly used for decision making. For example:
<?php
if ($add_line == TRUE) {
echo "<hr>";
}
?>

Note: The above example uses if..then statement for decision making. A detailed discussion about
how to use decisive logic is given in later lecture.
Integers
In PHP, integers can be based in decimal (10-based), hexadecimal (16-based) ,or octal (8-based)
notation, optionally preceded by a sign (- or +).
Important concept:
Decimal numbers have numerals 0, 1, 2, 3, 4, 5, 6, 7, 8, and 9.
Octal numbers have numerals 0, 1, 2, 3, 4, 5, 6, and 7.
Hexadecimal numbers have numerals 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, A, B, C, D, E, and F.
To define the base of a number, use the following rules:
if the default base is decimal, there is no need to precede the number with anything.
to use the octal notation, you must precede the number with a 0 (zero).
to use hexadecimal notation precede the number with 0x (zeroX).
To specify a positive or negative value, use the following rules:
numbers are positive by default.
to specify the negative value, precede the number with a negative "-" sign.
For example,
<?php
$myNo1 = 5678; // decimal number
$myNo2 = -5678; // a negative number
$myNo3 = 0123; // octal number (equivalent to 83 decimal)
$myNo4 = 0x1A; // hexadecimal number (equivalent to 26 decimal)
echo "$myNo1, $myNo2, $myNo3, $myNo4";
?>

Floating point numbers


Floating point numbers (also known as "floats", "doubles" or "real numbers") can be specified using
any of the following syntax:
Math format. Simply show the integer and the decimal fractions, such as 3.14125.
Scientific format. In scientific format, the natural logarithm (e) is used to denote the exponent.
For example, 6.25X1015 is expressed as 6.25+e15 (or simply 6.25e15), while 2.74X10-23 is 2.74e23. The natural logarithm letter distinction (e) is not case sensitive. You can use e or E to
express scientific formatted numbers.

PHP

16

Consider the following example:


<?php
$a = 3.125;
$b = 1.2e3;
$c = 5.27E-10;
echo "$a <br>";
echo "$b <br>";
echo "$c <br>";
?>

The output should look like this:


3.125
1200
5.27E-10

Strings
A string is series of characters. A string literal can be specified in two different ways.
Single quoted. The easiest way to specify a simple string is to enclose it in single quotes (the
character '). But, if you use single quotes (') for your string, all characters are printed as-is.
Double quoted. In PHP, escape sequences only work with double quotes (").
Consider the following example with double quotes,
<?php
echo "Line 1\nLine 2";
?>

The output should be:


Line 1
Line 2

However, when using single quotes,


<?php
echo 'Line 1\nLine 2';
?>

the output should change to (however, the \n is ignored by web browser):


Line 1\nLine 2

The most important difference between the two is that a string enclosed in double quotes is parsed
by PHP. This means that any variable in it will be expanded.
<?php
$var = 'apple<br>';
echo "$var"; // Results in the value of $var being printed
echo '$var'; // Results in the word '$var'
?>

The output is then:


apple
$var

PHP
Variable
PHP

There are a few rules that you need to follow when choosing a name for your PHP variables.
PHP variables must start with a letter an alpha charater.

17

Naming
Conventions

PHP variables may only be comprised of alpha-numeric characters and underscores. a-z, A-Z, 09, or _ .
Variables with more than one word should separate each word with an underscore character
( _ ). For example, $my_variable .

Do not use keywords and reserved words to name variable. They have special meaning in PHP.
Some keywords and reserved words represent functions, constants, or other PHP features.
Table: PHP Keywords
case
const
else
for
if
switch

and
continue
elseif
foreach
new
try

array
declare
endif
function
or
use var

as
default
extends
global
public
while

break
do
class
private
static
xor

According to PHP manual (http://us3.php.net/manual/en), $this is a special variable name that


cannot be assigned.
Predefined
variables

PHP provides a large number of predefined variables. They are a preferred method for retrieving
external variables. PHP itself creates some of the variables, while many of the other variables change
depending on which operating system and Web server PHP is running. Rather than attempt to
compile a complete listing of available predefined variables, you can run the following script to
display all of the available variables.
<?php
// Show all information, defaults to INFO_ALL
phpinfo();
?>

The following example will display the filename of the currently executing script, the type of web
browser or user agent that is being used to access the current script, the servers IP address, the
servers host name, and so on.
<?php
echo
echo
echo
echo
echo
echo
echo
?>

$_SERVER['PHP_SELF'] . "<br>";
$_SERVER['HTTP_USER_AGENT'] . "<br>";
$_SERVER['REMOTE_ADDR'] . "<br>";
$_SERVER['REQUEST_METHOD'] . "<br>";
$_SERVER['SERVER_NAME'] . "<br>";
$_SERVER['SERVER_SOFTWARE'] . "<br>";
$_SERVER['SERVER_PROTOCOL'];

You can use the following common predefined variable to retrieve information.

Variable Name
AUTH_TYPE
DOCUMENT_ROOT
HTTP_REFERER
HTTP_USER_AGENT
PATH_TRANSLATED

PHP

Table: Common Predefined Variables


Description Preview
When running under Apache as module doing HTTP authenticated this
variable is set to the authentication type.
Returns the full path of the website's document root defined in the web
server configuration.
This will return the URL of the referring page as a string, if there is a
referring page.
Will return the type of web browser or user agent that is being used to
access the current script.
Returns the translated path to the current script, not the
DOCUMENT_ROOT path.

18

PHP_AUTH_PW
PHP_AUTH_USER
PHP_SELF
REMOTE_ADDR
SCRIPT_FILENAME
SERVER_NAME

SERVER_PORT

When running under Apache as module doing HTTP authentication,


this variable is set to the password provided by the user.
When running under Apache as module doing HTTP authentication,
this variable is set to the username provided by the user.
The filename of the currently executing script, relative to the document
root.
Contains the IP address of the user requesting the PHP script from the
server.
Returns the full path to the executable that is executing the script.
Returns the name of the web server or virtual host that is processing the
request. For example, if you were visiting http://www.phpfreaks.com
the result would be www.phpfreaks.com.
Returns the current port of the server. Usually port 80 for NON-SSL
connections and port 443 for SSL connections.

To view a comprehensive list of Web server, environment, and PHP variables offered on your
particular system setup, simply visits the demo site
at:http://us3.php.net/manual/en/reserved.variables.server.php.
Review
Questions

1. Which escape sequence is equivalent to the [Tab] key?


A. \tab
B. /tab
C. \t
D. /t
2. Given the following code, what is the output?
<?php
$x = $y = 2;
echo ($y);
?>

A. 11
B. 9
C. 8
D. 2
3. Which is a string?
$a = "Hello, world!";
$b = "1 2/5";
$c = "02.23.72";

A. $a
B. $b
C. $c
D. All of the above
4. Which is a floating-point variable?
$a
$b
$c
$d

=
=
=
=

12;
972;
15.48;
-43;

A. $a
B. $b
PHP

19

C. $c
D. $d
5. In the following code, $larger is a __ variable.
<?php $larger = TRUE; ?>

A. Comparison
B. Boolean
C. Floating-point
D. Logical
6. The output of the following code is __.
<?php echo 0x1A; ?>

A. 25
B. 26
C. 81
D. 83
7. The output of the following code is __.
<?php
$x = 5;
$z = $y = $x;
echo $z;
?>

A. 5
B. $y
C. $y = $x
D. an error message
8. The output of the following code is __.
<?php
$y = ($x = 7);
echo $y;
?>

A. ($x = 7)
B. 7
C. $x = 7
D. $x
9. Which is a floating-point variable?
<?php
$a = 3.125;
$b = 1.2e3;
$c = 5.27E-10;
?>

A. $a
B. $b
C. $c
D. All of the above

PHP

20

10. Which is a possible output of the following code?


<?php echo $_SERVER['SERVER_NAME']; ?>

A. CISDEpt.com
B. 207.125.11.110
C. SNMP
D. /usr/cis246/test.php

PHP

21

Lab #2

PHP Variables, Data Types, and Expressions

Preparation #1: Running the server and create default database


1. Insert the USB that contains XAMPP. Determine the drive name (such as F:\).
2. Change to the X:\xampp\ directory (where X must be the correct drive name) to find the setup_xampp.bat
and then execute it. You should see:
######################################################################
# ApacheFriends XAMPP setup win32 Version
#
#--------------------------------------------------------------------#
# Copyright (C) 2002-2011 Apachefriends 1.7.7
#
#--------------------------------------------------------------------#
# Authors: Kay Vogelgesang (kvo@apachefriends.org)
#
#
Carsten Wiedmann (webmaster@wiedmann-online.de)
#
######################################################################
Do you want to refresh the XAMPP installation?
1) Refresh now!
x) Exit

3.

Press 1 and then [Enter]. If re-configuration succeeds, you should see the following message.
XAMPP is refreshing now...
Refreshing all paths in config files...
Configure XAMPP with awk for Windows_NT
###### Have fun with ApacheFriends XAMPP! ######
Press any key to continue ...

Learning Activity #1: declaring variable and assigning values to them


1. In the X:\xampp\htdocs\myphp directory (create the myphp subdirectory if it does not exist), use Notepad
to create a new file named lab2_1.php with the following contents:
<?php
$myinteger1 = 15; //declare an integer variable with value 15
$myinteger2 = -9; // negative number
echo $myinteger1 + $myinteger2 . "<br>"; //calculate the sum
$mystring1 = "An apple a day"; //declare a string with value
$mystring2 = "keeps doctors away!";
Use " " for blank space

echo $mystring1 . " " . $mystring2 . "<br>"; // concatenate strings


$float1 = 3.1412; //declare floating point variable with value
$float2 = 1.85e-3;
$float3 = 7.3e6;
echo $float1 * $float2 * $float3 . "<br>"; //multiplication
$first = "Nicole"; //use double quote to assign string
$last = 'Kidman'; //use single quote to assign string
$age = 43; // numbers need no quote
echo "$first $last is $age old!" . "<br>"; //double quote will parse
echo '$first $last is $age old!' . '<br>'; //single quote don't parse
//use html formatting tags to format PHP outputs
echo "World <u>history</u> is <b>his</b> story, not <i>mine</i>!<br>";

PHP

22

//use CSS to define style and use \ to escape sequence


echo "<div style=\"font-size:24px;color:red\">Those who teach do not
know!</div>";
?>

2.

Test the program. The output looks:

3.

Capture a screen shot similar to the above figure and paste it to a Word document named lab2.doc (or
lab2.docx).

Learning Activity #2:


1. In the X:\xampp\htdocs\myphp directory, use Notepad to create a new file named lab2_2.php with the
following contents:
<?php
$a = $b = $c = 12; // declare and assign the same values to variables
$a=$a+1; //let $a's new value = $a's old value (12) + 1
$b=$b-7; //let $b's new value = $b's old value (12) - 7
$c=$c/4; //let $c's new value = $c's old value (12) /4
echo "$a, $b, $c <br>"; //display new values of $a, $b, and $c
//hexadecimal and octal integers
$hex = 0xFF; // hexadecimal value
$oct = 0146; // octal value
echo "$hex - $oct <br>";
?>

2.

Test the program. The output looks:

3.

Capture a screen shot similar to the above figure and paste it to a Word document named lab2.doc (or
lab2.docx).

Learning Activity #3: String variables and concatenation


1. In the X:\xampp\htdocs\myphp directory, use Notepad to create a new file named lab2_3.php with the
following contents:

PHP

23

<?php
$word1="for";
$word2="ever";
$number1=12;
$number2=57;
// string-to-string concatenation
echo $word1 . $word2 . "<br>";
// string-to-number concatenation (become a new string)
echo $word1 . $number1 . "<br>";
// number-to-string concatenation (become a new string)
echo $number1 . $word1 . "<br>";
// number-to-number concatenation (a new string?)
echo $number1 . $number2 . "<br>";
$n = $number1 . $number2 . "<br>";
$n = $n / 4;
echo $n; // result is 314.25, so not necessary a new string
?>

2.

Test the program. The output looks:

3.

Capture a screen shot similar to the above figure and paste it to a Word document named lab2.doc (or
lab2.docx).

Learning Activity #4: Understanding Quotation marks


1. In the X:\xampp\htdocs\myphp directory, use Notepad to create a new file named lab2_4.php with the
following contents:
<?php
$course = 'CIS246';
$semester = "Fall";
echo '$course $semester<br>';
echo "$course $semester<br>";
echo 'I want to take $course.<br>';
echo "I want to take $course.<br>";
echo 'I won\'t see you in $semester.<br>';
echo "I won't see you in $semester.<br>";
echo "<hr size='1' width='100%'>";
echo "<hr size=\"1\" width=\"100%\">";
?>

2.

Test the program. The output looks:

PHP

24

3.

Capture a screen shot similar to the above figure and paste it to a Word document named lab2.doc (or
lab2.docx).

Learning Activity #5: Server Variables


1. In the X:\xampp\htdocs\myphp directory, use Notepad to create a new file named lab2_5.php with the
following contents:
<?php
echo
echo
echo
echo
echo
echo
echo
?>

"<h2>I see you</h2>";


"<b>Script Name</b>: ". $_SERVER['PHP_SELF'] . "<br>";
"<b>Your Browser</b>: ". $_SERVER['HTTP_USER_AGENT'] . "<br>";
"<b>Your IP address</b>:" . $_SERVER['REMOTE_ADDR'] . "<br>";
"<b>Server Host Name</b>:" . $_SERVER['SERVER_NAME'] . "<br>";
"<b>Web Server Software</b>: ". $_SERVER['SERVER_SOFTWARE'] . "<br>";
"<b>Transmission Protocol</b>: ". $_SERVER['SERVER_PROTOCOL'];

2.

Test the program. The output looks:

4.

Capture a screen shot similar to the above figure and paste it to a Word document named lab2.doc (or
lab2.docx).

Submitting the lab


1. Create a .zip file named lab2.zip containing:
Lab2_1.php
Lab2_2.php
Lab2_3.php
Lab2_4.php
Lab2_5.php
Lab2.doc (or .docx and make sure this file contains all the five screen shots)
2.

Upload the zipped file as response to question 11 or Assignment 2 (available in Blackboard).

PHP

25

Lecture #3:

Basic PHP Operators

Variable
and
operators

In order to work with strings and numbers to produce new values, your must learn PHP operators. An
operator is any symbol used to perform an operation, such as arithmetics operations: addition,
subtraction, multiplication, and division. The actual symbol used to perform the operation is known
as an operand.
The Assignment Operator
As introduced in the last article, the assignment operator allows you to assign a value to a variable.
You can assign strings, integers, even the results of functions. For example:
$greeting = "Good morning!";
$number = 12;
$myfunction = dispayTime(); \\will be discussed in later lecture

The Concatenation Operator


Concatenating two strings means sticking them together, one after another, creating a new string. For
example, the string "home" concatenated with the string "town" creates the string "hometown" . In
PHP, strings can be added to each other or additional values may be added to a string using the
concatenation operator ".". For example:
<?php
$age=21;
echo "The age is " . $age;
?>

The output is:


The age is 21

The concatenation operator allows you to append one value to another. You can append strings, other
variables or even the results of func tions. Consider the following example,
$var = "test";
$var2 = "This is a " . $var;
echo $var2;

This would output:


This is a test

You can also use what's called the Assignment Concatenation Operator ( .= )to append a new value
to the value an existing variable. For example:
$var = "An apple a day";
$var .=" keeps doctors away.";
echo $var;

This would output:


An apple a day keeps doctors away.

Arithmetic Operators
Just like in math, arithmetic operators in PHP are used to work with numbers. Addition, subtraction,
division, and multiplication are all supported:
Operand
PHP

Name

Sample

Description

26

+
*
/
%

Addition
Subtraction
Multiplication
Division
Modulus

$var1 + $var2
$var1 - $var2
$var1 * $var2
$var1/$var2
$var1%$var2

Adds the two values together.


Subtracts the second value from the first.
Multiplies the two values by each other.
Divides the first value by the second.
Returns the remainder of the first value divided
by the second.

Consider the following example,


<?php
$qty=15;
$price=2.71;
$amount = $qty * $price;
echo $amount;
?>

The $amount variable's value is determined by the calculation results of $qty and $price through the
multiplication operation (*). The resulting output is:
40.65

Incrementing/Decrementing Operators
PHP supports specific operators for incrementing (++) and decrementing (--) numbers. These provide
a short-hand way of expressing the increase or decrease of a value by the quantity one (1).
Depending on where you place the operator, it will take on a different order of operation. The table
below shows how the position of the operator affects the outcome of the variable $var.
Sample
Description
Operand Name
$var++; Returns $var, then increases it by 1.
++
Post-increment
++$var; Increases $var by 1, then returns it.
++
Pre-increment
$var--; Returns $var, then decreases it by 1.
-Post-decrement
--$var; Decreases $var by 1, the returns it.
-Pre-decrement
The following example illustrates the differences:
<?php
$a = $b =
echo $a++
echo ++$b
echo $c-echo --$d
?>

$c = $d =
. "<br>";
. "<br>";
. "<br>";
. "<br>";

3;
//increment
//increment
//decrement
//decrement

happens
happens
happens
happens

after $a is read
before $b is read
after $c is read
before $d is read

The output will be:


3
4
3
2

Increment and decrement also provides a way to perform skip counting.


Given two series A = {1, 4, 7, 10, 13} and B = {10, 8, 6, 4, 2, 0}; they both are incremented and
decremented by a number larger than 1. In such case, the increment and decrement operators are
denoted by:
+=n
-=n

where n is the increment or decrement. For example:


PHP

27

<?php
$x = 15; $y = 12;
$x+=5; $y-=2; //$x incremented by 5; $y decremented by 2
echo $x . "<br>";
echo $y;
?>

The output is:


20
10

20 is the result of 15 + 5, while 10 is the result of 12 - 2.


Comparison Operators
There are operators like == (equals) and > (greater than) that compare two expressions, giving a
result of true or false. As the name implies, they allow you to compare two values.
Operand
==
!=
<
>
<=
>=

===
!==

Name
equal to
not equal
to
less than
greater
than
less than or
equal to
greater
than or
equal to
identical to
not
identical to

Sample
$var1 == $var2
$var1 != $var2

Description
Is true if the first value is equivalent to the second.
Is true if the first value is not equal to the second.

$var1 < $var2


$var1 > $var2

Is true if the first value is less than the second.


Is true if the first value is greater than the second.

$var1 <= $var2

Is true if the first value is less than or equal to the


second.
Is true if the first value is greater than or equal to the
second.

$var1 >= $var2

$var1 ===
$var2
$var1 !==
$var2

Is true if the first value is equivalent to the second


and both are the same type.
Is true if the first value is not equal to the second or
they are not the same type

Consider the following example. The date() function will retrieve the current date and time from the
server computer, the argument "H" is a format character that tells PHP to show only the hour value.
<?php
$myHour = date("H"); // assign the hour value to $myHour variable
if ($myHour < 12) { // test the $myHour value with < operator
echo "Good morning!";
}
elseif ($myHour < 17) {
echo "Good afternoon!";
}
else {
echo "Good evening!";
}
?>

Go to http://members.lycos.co.uk/cistcom/hour.php to view the sample.


Later lectures will provide a detailed discussion about how comparison operators are used in decision
making.
Logical Operators
PHP

28

There are operators like && (AND) and || (OR) that enable you to create logical expressions that
yield true or false results. Logical operators are also called Boolean operator. They test conditions
and return tested result with logical value "FALSE" (or 0 representing false), and logical value
"TRUE" (or 1 representing true).
You can use the Truth Table below to learn how these operators work.
Inputs
A
B
0
0
0
1
1
0
1
1

and
A AND B
0
0
0
1

or
A OR B
0
1
1
1

not
!A
1
1
0
0

xor
xor(A,B)
0
1
1
0

Do not be intimidated by these academic terms! You actually use Boolean logic in your everyday
life. For example, you just heard a lady said "My name is Jennifer AND I am a doctor". If the lady is
actually named Megan or if she is actually a cook, then her statement would be false (the value is 0).
The statement above is actually made of two expressions or values: My name is Jennifer and I am
a doctor. Each of those, by itself, is true or false. The AND in the sentence is the logical operator,
which makes one expression out of two separate expressions.
When applying them to the truth table, "My name is Jennifer" is input A, while "I am a doctor" is
input B. The entire sentence is then denoted as A AND B. If her name is Jennifer (the value is 1 true) but she is not a doctor (the value is 0 - false), the statement is false according to the A AND B
example form the Truth Table, which says both A and B must be true for the
statement to be true.

Operand
AND
OR
XOR
&&
||
!

Name
and
or
exclusive or
and
or
not

PHP Logical Operators


Sample
Description
$var1 AND $var2
Is true if both values are true.
$var1 OR $var2
Is true if either value is true.
$var1 XOR $var2
Is true if either value is true, but not both.
$var1 && $var2
Is true if both values are true.
$var1 || $var2
Is true if either value is true.
!$var
Is true if the value is not true (ex. if the
variable doesn't exist).

For example, review the following code:


<?php
$s = 6;
$t = 5;
if ($s>4 AND $t>4) {echo "TRUE!"; }
?>

The output is 1 (indicating that the statement is true), because both condition $s>4 and $t>4 are
true.
You may have noticed that there are two different ways of performing a logical AND or OR in PHP.
The difference between AND and && (as well as between OR and ||) is the precedence used to
evaluate expressions. Later lectures will provide a detailed discussion about how logical operators
are used in decision making.
Bitwise operators
A bit is a representation of 1 or 0. Bitwise operators are used on integers. All bitwise operators
PHP

29

perform an operation on the one or more specified integer values as translated to binary expressions.
For example, the tilde or ~ (Bitwise NOT) operator changes binary 1s to 0s and 0s to 1s.
Example
$a & $b
$a | $b
$a ^ $b
~ $a
$a << n
$a >> n

Name
AND
OR
XOR
NOT
Shift left
Shift right

Result
Bits that are set in both $a and $b must be 1s to return 1.
Bits that are set in either $a or $b is 1 to return 1.
Bits that are set in $a or $b must be different to return 1.
Negate every bits set in $a. Turn 1 to 0, and vice versa.
Shift the bits of $a n steps to the left.
Shift the bits of $a n steps to the right.

Consider the following example, which outputs the integer 8.


<?php
$x = 9;
$y = 10;
echo $x & $y;
?>

To understand how the bitwise operator works, it is necessary to convert all the decimal integers 8
and 9 to their binary formats. For example, the integer 9 is equivalent to 1001 in binary and the
integer 8 is equivalent to 1010 in binary.
$x
$y
$x & $y

0
0
0

0
0
0

0
0
0

1
1
1

0
0
0

0
0
0

0
1
0

1
0
0

The AND (&) bitwise operator requires bits that are set in both $x and $y must be 1s to return 1. In
the above table, there is only one case that meets the criteria. The operation $x & $y yields a new
binary value 1000, which equals 8 in decimal format. PHP displays only the decimal results, so the
output is 8.
The OR (|) bitwise operator requires bits that are set in either $x or $y is 1 to return 1. According to
the following table, the $x | $y operation yields 1011 in binary or 11 in decimal format. The output
is 11.
$x
$y
$x | $y

0
0
0

0
0
0

0
0
0

1
1
1

0
0
0

0
1
1

0
0
0

1
0
1

The XOR (exclusive or) operator requires bits that are set in $x and $y must be different to return 1.
The $x ^ $y operation yields 11 in binary or 3 in decimal format. The output is 3.
$x
$y
$x ^ $y

0
0
0

0
0
0

0
0
0

0
0
0

1
1
0

0
1
1

0
0
0

1
0
1

The NOT (~) bitwise operator negates every bit in $x, meaning to turn every 1 to 0 and vice versa. $x
in binary is 1001, so ~$x is 0110. The operation ~$x & $y yields 0010, which is 2 in decimal.
$x
~$x
$y
~$x & $y

1
0
1
0

0
1
0
0

0
1
1
1

1
0
0
0

The Shift Left (<<) operator shifts the bits of $x n steps to the left. For example, $x << 2 yields a
new number 100100 or 36 in decimal format.
PHP

30

$x
$x << 2

1
0

0
1

0
0

1
0

Shift right (>>)operator shifts the bits of $x n steps to the right. For example, $x >> 2 yields a new
number 10 or 2 in decimal format.
$x
$x >> 2

0
1

1
0

If you are storing integer data (such as normal decimal values like the 150 and 75 mentioned earlier)
and want to perform internal translation to do binary math, use bitwise operators. Bitwise operators
are also valuable to get a NOT value which is not necessarily the exact opposite.
The
Execution
Operators

PHP is originally created for use in a Unix environment, so it naturally supports one Unix-based
execution operator--the backquote (``). Note that these are not single-quotes. In the generic keyboard.
The backquote key looks:

~
`
Consider the following example. The statement ls l is an Unix statement. If your Web server is
a Unix/Linux server, the following will display the contents of the presently working directory.
<?php
$str = `ls -al`;
echo "<pre>$str</pre>";
?>

This operator simulates a shell prompt and executes the command as a shell command; the output
will be returned a string. This operator is functionally similar to the shell_exec() function, which
executes command via shell and return the complete output as a string. For example:
<?php
$str = shell_exec('ls -al');
echo "<pre>$str</pre>";
?>

The eval() function evaluates a string as PHP code, meaning it can convert a command-like string
into a PHP code temporarily. For example:
<?php
$x = 3.1415;
$str = "var_dump($x);";
echo $str . "<br>"; // output the string
eval("$str"); // run the string as PHP code
?>

The output looks:


var_dump(3.1415);
float(3.1415)

However, the string passed must be valid PHP code, including things like terminating statements
with a semicolon so the parser does not die on the line after the eval().
Type
casting in
PHP

PHP is a loosely typed language, meaning its variables types are determined by the values of the
variables. Although many programmers arguably believe type casting is not important to PHP, there

31

PHP

are ways to cast types in PHP.


The var_dump() function displays information about type and value of a variable. For example:
<?php
$PI = 3.1415;
$y = true;
var_dump($x, $y);
?>

The output will be:


float(3.1415) bool(true)

Since the var_dump() function displays structured information including its type and value, it helps
to understand why PHP is loosely typed. Consider the following example. The string variable $var
is assigned two characters 1 and 2 to make new string 12.
<?php
$var = "12"; // 12 is declared as string
echo $var + 3 . "<br>"; // 15
var_dump($var); // string(2) "12"
$var++; // increment by 1
echo $var . "<br>"; // 13
var_dump($var); // int(13)
?>

The statement $var + 3 uses an arithmetic operator to add 3 to the string 12. In a well-structured
language such as C++ and Java, a string cannot be calculated by arithmetic operator and two
dissimilar types cannot be added by the addition operator. However, PHP allows such calculation
by temporarily cast the type of $var and let the value it holds determining its type. Consequently, the
output of the following statement is 15.
echo $var + 3 . "<br>";

Such type casting is temporary, meaning it only applies to the above statement. When being tested by
the var_dump() function, as shown below, the output string(2) "12" still indicates that $var is a
string variable with two character value 12.
var_dump($var);

The next statement $var++ forces the variable to increment by 1 and it also forces the $var variable
to cast its type to integer. Finally, the output is int(13) when the var_dump() function displays its
type and value.
PHP has the ability to automatically cast variable types, and this is an advantage. However, when it
comes to the time that a programmer absolutely must fix the variable to a particular type, the need to
cast variable rises.
Review
Questions

1. Given the following code, what is the output?


<?php
$age=21;
echo "The age is " . $age;
?>

A. The age is 21
B. The age is $age
PHP

32

C. The age is
D. "The age is " . $age
2. Given the following code, what is the output?
<?php
$age="12";
$age=$age . "1";
echo $age;
?>

A. 12.1
B. 13
C. 121
D. $age
3. Given the following code, what is the output?
<?php
$str1 = "CIS";
$str2 = "246";
echo $str1 . $str2;
?>

A. CIS . 246
B. CIS.246
C. CIS246
D. CIS246
4. Given the following code, what is the output?
<?php
$n = 7;
$n = $n * 3;
echo $n
?>

A. 7 * 3
B. $n * 3
C. 7
D. 21
5. Given the following code, what is the output?
<?php
$x=4;
echo ++$x;
?>

A. 4
B. 5
C. ++4
D. ++$x
6. Given the following code, what is the output?
<?php
$y = 15;
echo $y+=5;

PHP

33

?>

A. 15
B. 10
C. 20
D. $y+=5
7. Given the following code, what is the output?
<?php
$x = 9;
$y = 10;
echo ($x | $y);
?>

A. 11
B. 9
C. 8
D. 2
8. Given the following code, what is the output?
<?php
$x = 9;
echo ($x << 2);
?>

A. 18
B. 29
C. 36
D. 27
9. Given the following code, what is the output?
<?php
$x = 256;
$x = (string) $x;
var_dump($x);
?>

A. string "256"
B. string("256")(3)
C. string(3) "256"
D. string("256")
10. Which increments a variable $m by 4?
A. $m=$m++4;
B. $m+=4;
C. $m=+4;
D. $m++4;

PHP

34

Lab #3

Basic PHP Operators

Preparation #1: Running the server and create default database


1. Insert the USB that contains XAMPP. Determine the drive name (such as F:\).
2. Change to the X:\xampp\ directory (where X must be the correct drive name) to find the setup_xampp.bat
and then execute it. You should see:
######################################################################
# ApacheFriends XAMPP setup win32 Version
#
#--------------------------------------------------------------------#
# Copyright (C) 2002-2011 Apachefriends 1.7.7
#
#--------------------------------------------------------------------#
# Authors: Kay Vogelgesang (kvo@apachefriends.org)
#
#
Carsten Wiedmann (webmaster@wiedmann-online.de)
#
######################################################################
Do you want to refresh the XAMPP installation?
1) Refresh now!
x) Exit

3.

Press 1 and then [Enter]. If re-configuration succeeds, you should see the following message.
XAMPP is refreshing now...
Refreshing all paths in config files...
Configure XAMPP with awk for Windows_NT
###### Have fun with ApacheFriends XAMPP! ######
Press any key to continue ...

Learning Activity #1: Arithmetic & increment/decrement operators


1. In the X:\xampp\htdocs\myphp directory (create the myphp subdirectory if it does not exist), use Notepad
to create a new file named lab3_1.php with the following contents:
<?php
//Post-increment
$a = 7;
echo $a++ . "<br />\n";
echo $a . "<br />\n";
//Pre-increment
$a = 7;
echo ++$a . "<br />\n";
echo $a . "<br />\n";
//Post-decrement
$a = 7;
echo $a-- . "<br />\n";
echo $a . "<br />\n";
//Pre-decrement
$a = 7;
echo --$a . "<br />\n";
echo $a . "<br />\n";
$x =
echo
echo
echo

PHP

5;
($x += 5) . "<br />\n";
($x -= 2) . "<br />\n";
($x /= 4) . "<br />\n";

//add 5
//minus 5
//divided by 4

35

echo ($x *= 3) . "<br />\n";


$msg
$msg
$msg
$msg
echo
?>

//multiplied by 3

= "This is sentence 1.";


.= "This is sentence 2."; // concatenation
.= "This is sentence 3.";
.= "This is sentence 4.";
$msg;

2.

Test the program with a Apache server (XAMPP).

3.

Capture a screen shot similar to the above figure and paste it to a Word document named lab3.doc (or
lab3.docx).

Learning Activity #2: Logical/Comparison operators and escape sequence


1. In the X:\xampp\htdocs\myphp directory, use Notepad to create a new file named lab3_2.php with the
following contents:
<?php
$x = rand(50, 99);

// random number 50 ~ 99

if ($x>=90) { $gd = "A"; }


elseif ($x>=80) { $gd = "B"; }
elseif ($x>=70) { $gd = "C"; }
elseif ($x>=60) { $gd = "D"; }
else { $gd = "F"; }
echo $x . " points get you a(n) " . $gd . ".<br>";
$a = rand(1, 9); // random number 1 ~ 9
$b = rand(1, 9);
if ($a > $b) { $str = "$a > $b"; }
elseif ($a < $b) { $str = "$a < $b"; }
else { $str = "$a = $b"; }
echo $str . "<br>";
$s = rand(1, 9);
$t = rand(1, 9);
if ($s>4 AND $t>4) {echo "$s>4 AND $t>4 is TRUE!<br>"; }
else { echo "$s>4 AND $t>4 is FALSE!<br>"; }
$m = rand(1, 9);
$n = rand(1, 9);
if ($m>5 OR $n>5) {echo "$m>5 OR $n>5 is TRUE!<br>"; }
else { echo "$m>5 OR $n>5 is FALSE!<br>"; }
echo "<hr size=1 width=100%">
$i = 6;
$j = 5;

PHP

36

// letter-based logical Operators


\" escapes the sequence for "
if ($i>4 AND $j>4) {
echo "The statement \"$i > 4 and $j > 4\" is TRUE!<br>"; }
if ($i>4 OR $j>4) {
echo "The statement \"$i > 4 or $j > 4\" is TRUE!<br>"; }
if ($i<4 XOR $j>4) {
echo "The statement \"Either $i < 4 or $j > 4\" is False!<br>"; }
echo "<hr size=1 width=100%>";
// symbol-based logical Operators
if ($i>4 && $j>4) {
echo "The statement \"$i > 4 and $j > 4\" is TRUE!<br>"; }
if ($i>4 || $j>4) {
echo "The statement \"$i > 4 or $j > 4\" is TRUE!<br>"; }
if (!$i<4 && !$j<4) {
echo "The statement \"Neither $i nor $j is less than 4\" is TRUE!<br>"; }
?>

2.

Test the program. A sample output looks:

3.

Capture a screen shot similar to the above figure and paste it to a Word document named lab3.doc (or
lab3.docx).

Learning Activity #3: Increment/decrement by number other than 1


1. In the X:\xampp\htdocs\myphp directory, use Notepad to create a new file named lab3_3.php with the
following contents:
<?php
//increment and decrement by 1
$x = 4; $y = 9;
$x++;
$y--;
echo "$x, $y <br>"; //display the new value of $x and $y
//increment and decrement by 2 or larger number
$m = 11;
$n = 6;
$m+=4; //increment by 4
$n-=3; //decrement by 3
echo "$m, $n <br>"; //display the new value of $m and $n
$i=5;
$i+=2;
$j=5;
$j=$j+2;

PHP

// so, $j+=2 means $j=$j+2

37

echo "$i, $j <br>";


$b = ($i==$j); // verify if $i=$j
var_dump($b); echo "<br>";
$s=9;
$s-=5;
$t=9;
$t=$t-5; // so, $s-=5 means $s=$s-5
echo "$s, $t <br>";
$b = ($s==$t); // verify if $s=$t
var_dump($b); echo "<br>";
?>

2.

Test the program. The output looks:

3.

Capture a screen shot similar to the above figure and paste it to a Word document named lab3.doc (or
lab3.docx).

Learning Activity #4: Bitwise operator


1. In the X:\xampp\htdocs\myphp directory, use Notepad to create a new file named lab3_4.php with the
following contents:
<?php
$x = 9;
$y = 10;
echo '$x & $y: <b>' . ($x & $y) .
echo '$x | $y: <b>' . ($x | $y) .
echo '$x ^ $y: <b>' . ($x ^ $y) .
echo '~$x & $y: <b>' . (~$x & $y)
echo '$x << 2: <b>' . ($x << 2) .
echo '$x >> 2: <b>' . ($x >> 2) .
echo
$a =
$b =
echo
echo
echo
echo
echo
echo
echo
?>

2.

"<hr size=1 width=100%>";


rand(1,9);
rand(1,9);
'$a is ' . $a . ', $b is ' .
'$a & $b: <b>' . ($a & $b) .
'$a | $b: <b>' . ($a | $b) .
'$a ^ $b: <b>' . ($a ^ $b) .
'~$a & $b: <b>' . (~$a & $b)
'$a << 2: <b>' . ($a << 2) .
'$a >> 2: <b>' . ($a >> 2) .

"</b><br>";
"</b><br>";
"</b><br>";
. "</b><br>";
"</b><br>";
"</b><br>";

$b . "<br>";
"</b><br>";
"</b><br>";
"</b><br>";
. "</b><br>";
"</b><br>";
"</b><br>";

Test the program. A sample output looks:

PHP

38

3.

Capture a screen shot similar to the above figure and paste it to a Word document named lab3.doc (or
lab3.docx).

Learning Activity #5: Type casting


1. In the X:\xampp\htdocs\myphp directory, use Notepad to create a new file named lab3_5.php with the
following contents:
<?php
$var = "12"; // 12 is declared as string
echo $var + 3 . "<br>";
var_dump($var);
echo "<br>"; //display the variable type and value
echo $var . "<br>";
$var++;
echo $var . "<br>";
var_dump($var); //display the variable type and value
echo "<hr size=1 width=100%>";
$x = 256; // 256 is a number, $x is numeric variable
var_dump($x);
echo "<br>";
$x = (string) $x; // cast to string type
var_dump($x);
echo "<br>";
echo "<hr size=1 width=100%>";
$a = "39812"; // string variable
var_dump($a);
echo "<br>";
$a = (int) $a; // cast to integer
var_dump($a);
echo "<br>";
echo "<hr size=1 width=100%>";
$PI = 3.14159265; // float variable
var_dump($PI);
echo "<br>";
$PI = (string) $PI; // cast to string
var_dump($PI);
echo "<br>";
echo "<hr size=1 width=100%>";
$b = 0; // integer
var_dump($b);
echo "<br>";

PHP

39

$b = (bool) $b; // cast to Boolean


var_dump($b);
echo "<br>";
?>

2.

Test the program. The output looks:

3.

Capture a screen shot similar to the above figure and paste it to a Word document named lab3.doc (or
lab3.docx).

Submitting the lab


1. Create a .zip file named lab3.zip containing:
lab3_1.php
lab3_2.php
lab3_3.php
lab3_4.php
lab3_5.php
Lab3.doc (or .docx and make sure this file contains all the five screen shots)
2.

Upload the zipped file as response to question 11 or Assignment 3 (available in Blackboard).

PHP

40

Lecture #4

PHP Arrays

Introduction

An array in PHP is actually an ordered list that stores multiple values. All items in the list have at
least one thing in common that set the sequence of values of the item. For example, there are four
seasons in a year. Winter must come before spring, spring must come before summer, and more.
Season is the name of array, which contains four items, spring, summer, fall, and winter, in
sequence.
In PHP, it's easy to create and initialize PHP arrays. There are two methods to choose from, and
we'll be discussing both of them in this lecture. You can
create an array with the array identifier.
create an array with the array() function.
Create an array with the array identifier
The simplest way to create a PHP array is to use the array identifier, which is a set of empty square
brackets. For example:
$season[0]="Spring";
$season[1]="Summer";
$season[2]="Fall";
$season[3]="Winter";

The syntax is:


ArrayName[index]=value

By default, the index numbers start at zero, and arrays are assumed to be zero-based. This means
that the index number of the last element is typically one less than the number of elements. In other
words, if an array has four elements, the last value will be referenced as $season[3].
You can create an array, in PHP, by simply assigning values. For example:
$season[]="Spring";
$season[]="Summer";
$season[]="Fall";
$season[]="Winter";

PHP will automatically assign the index value for each element in the array. Try the following two
examples; they will yield the same results.
<?php
$a[0]="Apple";
$a[1]="Orange";
$a[2]="Banana";
$a[3]="Tangerine";
echo $a[0] . " : 1st item.<br>";
echo $a[3] . " : 4th item.<br>";
?>

<?php
$a[]="Apple";
$a[]="Orange";
$a[]="Banana";
$a[]="Tangerine";
echo $a[0] . " : 1st item.<br>";
echo $a[3] . " : 4th item.<br>";
?>

The output for both examples will look like:


Apple :1st item.
Tangerine : 4th item.

Create an array with the array() function


In PHP, you can specify an array with array(). This is the method of choice when you have multiple
values to assign at one time. For example:
PHP

41

$season = array("Spring","Summer","Fall","Winter");

Each element is surrounded by quotes and separated by commas. The number of elements is
variable, so you can specify as many elements as you need to initialize the array. For example:
<?php
$season = array("Spring","Summer","Fall","Winter");
echo $season[2] . '($season[2]) gets the 3rd item.';
echo $season[3] . '($season[3]) gets the 4th item.';
?>

will yield the following output:


Fall($season[2]) gets the 3rd item.Winter($season[3]) gets the 4th item.

Be sure to review the previous section to understand why the $season[2] value enclosed by single
quotes (') are escaped.
Defining the starting index value
By default, PHP arrays are zero-based. This means that the index value for the last element is
always one less than the total number of elements. If you have an array of all 50 US states, the first
element would be $states[0], and the last one will be accessed as $states[49]. If you'd like to change
the default behavior, use the => operator. For example:
$state = array(1 => "Alabama", "Alaska", "California");

Consequently the first element, "Alabama", would be accessed as $state[1] instead of the default
$state[0]. Compare the following codes and their results.
<?php
$state = array(1 => "Alabama", "Alaska", "California");
echo $state[0];
?>

The output is Some kind of error message like "Undefined offset: 0". Now try,
<?php
$state = array(1 => "Alabama", "Alaska", "California");
echo $state[1];
?>

The output is:


Alabama

In PHP, there are three kind of arrays:


Numeric array - An array with a numeric index.
Associative array - An array where each ID key is associated with a value.
Multidimensional array - An array containing one or more arrays.
All the above examples are numeric array. It is time to move on to associative array.
Creating Associative Arrays in PHP
When you create a simple PHP array, the starting index value is zero by default. However, you can
use string values as the index for each element in the array. When a PHP array uses strings for the
index values, it is known as an associative array.
Option 1: Create associative arrays with the array() function
PHP

42

To create an associative array in PHP, the easiest way is to use the array() function. However,
unlike a simple PHP array, an associative array in PHP needs both the index value, known as the
key, and the value of the element, known as the value. These are often referred to as key-value
pairs. Here's an example:
$StateCapital = array("AL"=> "Montgomery", "LA"=> "Baton Rouge",
"TX"=> "Austin");

The example uses the two letter abbreviation for Alabama, Louisiana, and Texas as the key, or
index value. The capitals for those states, Montgomery, Baton Rouge, and Austin, are the values.
Notice that keys and values are separated by '=>', and each key-value pair is separated by commas.
Option 2: Create associative arrays with the array identifier
Another way to create associative arrays in PHP is to use the array identifier.
$StateCapital["AL"] = "Montgomery";
$StateCapital["LA"] = "Baton Rouge";
$StateCapital["TX"] = "Austin";

For example:
<?php
$gender["F"]="Female";
$gender["M"]="Male";
$gender["U"]="Unidentifiable";
echo "Jennifer Lopez is " . $gender["F"] ."!";
?>

will yield the following output:


Jennifer Lopez is Female!

The following will yield "Bill Clinton is Male!":


<?php
$gender = array("F"=>"Female", "M"=>"Male", "U"=>"Unidentified");
echo "Bill Clinton is " . $gender["M"] ."!";
?>

Note that you can use both methods on the same array to add new elements.
$StateCapital = array("AL"=> "Montgomery", "LA"=> "Baton Rouge",
"TX"=> "Austin");
$StateCapital["CA"] = "Sacramento";

Consider the following example, the $StateCapital["CA"] element is added after the array is created,
and the output is Sacramento.
<?php
$StateCapital = array("AL"=> "Montgomery", "LA"=> "Baton Rouge",
"TX"=> "Austin");
$StateCapital["CA"] = "Sacramento";
echo "The state capital of California is " . $StateCapital["CA"];
?>

One thing to keep in mind is that your keys, or index values, should be short and meaningful. Not
only will it be easier to maintain and modify your PHP script, but the script will also run more
PHP

43

efficiently.
Another good thing to remember is not to access an associative array value within a string. Since the
keys and values are enclosed in double quotations, they can't be embedded within a string. Instead,
use the concatenation operator to combine the string values.
Array is very useful to the design of dynamic web site. The following PHP code will randomly
display different graphics with hyperlink. Portal web sites, such as MSN.com and Yahoo.com, use
these techniques to randomly display advertisement on their sites.
<?php
$r = rand(0,9); //using rand() to generate random number
$graphic = array( //array of graphic file name
"01.gif",
"02.gif",
"03.gif",
"04.gif",
"05.gif",
"06.gif",
"07.gif",
"08.gif",
"09.gif",
"10.gif",
);
//use concatenation operator to combine file name to web site URL
$image ="http://www.mysite.com/images/" . $graphic[$r];
$url = array( // array of sites to link with each graphic
"http://www.cnn.com",
"http://www.nbc.com",
"http://www.abc.com",
"http://www.fox.com",
"http://www.mtv.com",
"http://www.hbo.com",
"http://www.pbs.com",
"http://www.tnt.com",
"http://www.tmc.com",
"http://www.upn.com",
"http://www.cbs.com"
);
echo "<a href=$url[$r]>";
echo "<img src=$image border=0></a>";
?>

Note: When you visit this site, click Refresh on the web browser toolbar to see how the code
displays different graphics dynamically.
Multi-Dimensional Arrays
PHP arrays can contain arrays. In other words, a multidimensional array is an array except that
holds other arrays as a value (in the regular key=>value pair of an array), which in turn hold other
arrays as well. For example, the following code creates three arrays: $SF, $Action, and $Romance.
$SF = array("2001", "Alien","Terminator");
$Action = array("Swing Girls","Premonition","Infection");
$Romance = array("Sleepless in Seattle","You've Got Mail","All of Me");

A multidimensional array however, will contain another array as a possible value; for example, the
PHP

44

$genre super-array contains all the three arrays.


<?php
$genre = array (
"SF" => array("Star Wars", "Alien","Terminator"),
"Action" => array("Swing Girls","Premonition","Infection"),
"Romance" => array("Sleepless in Seattle","You've Got
Mail","All of Me")
);
print_r($genre);
?>

The SF, Action, and Romance are three individual arrays, but they are now elements to the
genre array. So the output of the above code looks:
Array
(
[SF] => Array
(
[0] => Star Wars
[1] => Alien
[2] => Terminator
)
[Action] =>
(
[0]
[1]
[2]
)

Array
=> Swing Girls
=> Premonition
=> Infection

[Romance] => Array


(
[0] => Sleepless in Seattle
[1] => You've Got Mail
[2] => All of Me
)
)

The above sample output shows the hierarchy of the genre array and its element arrays. You can
interpret the hierarchy using the format of: $genre["SF"][0] = "Star War". Formally, the
syntax is:
parentArrayName["childArrayName"]["childElementKey"];

The following example further explains how to display values of each of the elements.
<?php
$genre = array (
"SF" => array("Star Wars", "Alien","Terminator"),
"Action" => array("Swing Girls","Premonition","Infection"),
"Romance" => array("Sleepless in Seattle","You've Got
Mail","All of Me")
);
echo $genre["SF"][0] . "<br />";
echo $genre["SF"][1] . "<br />";
echo $genre["SF"][2] . "<br />";
echo $genre["Action"][0] . "<br />";

PHP

45

echo $genre["Action"][1] . "<br />";


echo $genre["Action"][2] . "<br />";
echo $genre["Romance"][0] . "<br />";
echo $genre["Romance"][1] . "<br />";
echo $genre["Romance"][2] . "<br />";
?>

The same format applies to number-based array. For example:


<?php
$lists = array ( 1 => array( 12, 14, 16), 2 => array(11, 13, 15) );
print_r($lists);
?>

The output looks,


Array
(
[1] => Array
(
[0] => 12
[1] => 14
[2] => 16
)
[2] => Array
(
[0] => 11
[1] => 13
[2] => 15
)
)

To display each value, use:


<?php
$lists = array ( 1 => array( 12, 14, 16), 2 => array(11, 13, 15) );
echo $lists["1"][0] . "<br>\n";
echo $lists["1"][1] . "<br>\n";
echo $lists["1"][2] . "<br>\n";
echo $lists["2"][0] . "<br>\n";
echo $lists["2"][1] . "<br>\n";
echo $lists["2"][2] . "<br>\n";
?>

Review
Questions

1. Given the following code, what is the output?


<?php
$n = array(1, 2, 3, 4);
echo $n[3];
?>

A. 1
B. 2
C. 3
D. 4

PHP

46

2. Given the following code, what is the output?


<?php
$n = array(1, 2, 3, 4);
echo $n[0]+$n[3];
?>

A. 5
B. 6
C. 7
D. 8
3. Given the following code, what is the output?
<?php
$a[] = 1;
$a[] = 2;
$a[] = 3;
$a[] = 4;
echo $a[2];
?>

A. 1
B. 2
C. 3
D. 4
4. Given the following code, what is the output?
<?php
$a[2] = 1;
$a[3] = 2;
$a[6] = 3;
$a[9] = 4;
echo $a[2];
?>

A. 1
B. 2
C. 3
D. 4
5. Given the following code:
<?php
$course["cis245"]
$course["cis246"]
$course["cis247"]
$course["cis248"]
?>

=
=
=
=

"Perl Programming";
"PHP Programming";
"Python Programming";
"Plank Programming";

which generate the following output?


PHP Programming

A. <?php print $course["cis245"]


B. <?php print $course["cis246"]
C. <?php print $course["cis247"]
D. <?php print $course["cis248"]

PHP

47

6. Given the following code,


<?php
$fruit = array("A" => "Apple",
"B" => "Banana",
"G" => "Grape",
"O" => "Orange"); ?>

which generate the following output?


I like banana!

A. print "I like " + $fruit["B"] . "!";


B. print "I like " . $fruit["B"] . "!";
C. print "I like " $fruit["B"] "!";
D. print "I like " + $fruit["B"] + "!";
7. Given the following code, which is the correct output?
<?php
$state = array(1 => "Alabama", "Alaska", "California", "Nevada");
echo $state[3];
?>

A. Alabama
B. Alaska
C. California
D. Nevada
8. Given the following code, which combination can yield a result of 10?
<?php $x = array( 9, 6, 4, 2, 5, 8, 9); ?>

A. $x[3] + $x[5];
B. $x[0] + $x[4] - $x[2];
C. $x[2] * $x[4];
D. $x[1] + $x[6];
9. Given the following code, which displays the value 99?
<?php $x = array ( 1 => array( 101, 102), 2 => array(100, 99) ); ?>

A. echo $x["1"][0];
B. echo $x["1"][1];
C. echo $x["2"][0];
D. echo $x["2"][1];
10. Given the following code, which displays the value Infection?
<?php
$genre = array (
"SF" => array("Star Wars", "Alien","Terminator"),
"Action" => array("Swing Girls","Premonition","Infection"),
"Romance" => array("Sleepless in Seattle","You've Got
Mail","All of Me")
); ?>

A. echo $genre["Action"][0] . "<br />";


B. echo $genre["Action"][1] . "<br />";
PHP

48

C. echo $genre["Action"][2] . "<br />";


D. echo $genre["Action"][3] . "<br />";

PHP

49

Lab #4

PHP Arrays

Preparation #1: Running the server and create default database


1. Insert the USB that contains XAMPP. Determine the drive name (such as F:\).
2. Change to the X:\xampp\ directory (where X must be the correct drive name) to find the setup_xampp.bat
and then execute it. You should see:
######################################################################
# ApacheFriends XAMPP setup win32 Version
#
#--------------------------------------------------------------------#
# Copyright (C) 2002-2011 Apachefriends 1.7.7
#
#--------------------------------------------------------------------#
# Authors: Kay Vogelgesang (kvo@apachefriends.org)
#
#
Carsten Wiedmann (webmaster@wiedmann-online.de)
#
######################################################################
Do you want to refresh the XAMPP installation?
1) Refresh now!
x) Exit

3.

Press 1 and then [Enter]. If re-configuration succeeds, you should see the following message.
XAMPP is refreshing now...
Refreshing all paths in config files...
Configure XAMPP with awk for Windows_NT
###### Have fun with ApacheFriends XAMPP! ######
Press any key to continue ...

Learning Activity #1: Creating arrays using array() function


1. In the X:\xampp\htdocs\myphp directory (create the myphp subdirectory if it does not exist), use Notepad
to create a new file named lab4_1.php with the following contents:
<?php
// Programmer: Penn Wu
// array of numbers
$n = Array (1, 3, 5, 7);
echo
echo
echo
echo

$n[0]
$n[1]
$n[2]
$n[3]

.
.
.
.

'
'
'
'

is
is
is
is

$n[0]!<br>';
$n[1]!<br>';
$n[2]!<br>';
$n[3]!<br>';

echo "<hr width=100%>";


// array of strings
$tip= Array ("Right click the mouse!",
"Double click the mouse!",
"Double right click the mouse!",
"Press F8 and F12!",
"Find the ANY key!",
"Press Shift+Ctrl+Alt+Del!",
"Hold the Esc key for 2 seconds!");
// generate random number from 0 to 6
$i=rand(0,6);

PHP

50

echo "Tip of the day is: <b>" . $tip[$i] . "</b>";


echo "<hr width=100%>";
// Associative Array
$school = Array("UCI"=>"University of California, Irvine",
"UCSD"=>"University of California, San Diego",
"UCLA"=>"University of California, Los Angeles",
"UCD"=>"University of California, Davis");
echo
echo
echo
echo

$school["UCI"] . "<br>";
$school["UCLA"] . "<br>";
$school["UCD"] . "<br>";
$school["UCSD"] . "<br>";

?>
2.
3.

Test the program with a Apache server (XAMPP).


Test the script. It looks:

4.

Capture a screen shot similar to the above figure and paste it to a Word document named lab4.doc (or
lab4.docx).

Learning Activity #2: Creating arrays using array identifier


1. In the X:\xampp\htdocs\myphp directory, use Notepad to create a new file named lab4_2.php with the
following contents:
<?php
// Programmer: Penn Wu
//using array identifier
$weekday[0]="Sunday"; // with index (aka key)
$weekday[1]="Monday";
$weekday[2]="Tuesday";
$weekday[3]="Wednesday";
$weekday[4]="Thursday";
$weekday[5]="Friday";
$weekday[6]="Saturday";
$week = date("w"); // Number of the day of the week; 0 for Sunday
echo "Today is a $weekday[$week] of "; // $weekday value is subject to $week
$month[1]="Jan"; // without index (aka key)
$month[2]="Feb";
$month[3]="Mar";
$month[4]="Apr";
$month[5]="May";
$month[6]="Jun";
$month[7]="Jul";
$month[8]="Aug";
$month[9]="Sep";

PHP

51

$month[10]="Oct";
$month[11]="Nov";
$month[12]="Dec";
$Mnumber = date("n"); // Number of a month without leading zeros (1 - 12)
echo "$month[$Mnumber]!<br>"; // $month value is subject to $Mnumber
?>
2.
3.

Test the program with a Apache server (XAMPP).


Test the script. It looks similar to:

4.

Capture a screen shot similar to the above figure and paste it to a Word document named lab4.doc (or
lab4.docx).

Learning Activity #3: Adding new elements including associative elements


1. In the X:\xampp\htdocs\myphp directory, use Notepad to create a new file named lab4_3.php with the
following contents:
<?php
// Programmer: Penn Wu
// create an array with 2 elements
$subject=Array("Chemistry","Physics");
// add new elements
$subject[2]="Management";
$subject[3]="Marketing";
// add new associative element
$subject["Bio"]="Biology";
$subject["Chem"]="Chemistry";
$subject["Acct"]="Accounting";
echo
echo
echo
echo
echo
echo
echo
?>
2.
3.

'$subject[0] is ' . $subject[0] . "!!<br>";


'$subject[1] is ' . $subject[1] . "!!<br>";
'$subject[2] is ' . $subject[2] . "!!<br>";
'$subject[3] is ' . $subject[3] . "!!<br>";
'$subject["Bio"] is ' . $subject["Bio"] . "!!<br>";
'$subject["Chem"] is ' . $subject["Chem"] . "!!<br>";
'$subject["Acct"] is ' . $subject["Acct"] . "!!<br>";

Test the program with a Apache server (XAMPP).


Test the script. It looks:

PHP

52

4.

Capture a screen shot similar to the above figure and paste it to a Word document named lab4.doc (or
lab4.docx).

Learning Activity #4:


1. In the X:\xampp\htdocs\myphp directory, use Notepad to create a new file named lab4_4.php with the
following contents:
<?php
// Programmer: Penn Wu
//using array() function
$tip= array(
"The secret of life is...It's a secret.",
"Good advice jars the ear.",
"Bloom where you are planted.",
"The greatest danger could be your stupidity.",
"Your heart desires to give money to the poor.",
"Work hard and happiness will come your way.",
"Love is coming your way."
);
$week = date("w"); // Number of the day of the week; 0 for Sunday
echo "Tip of the day: ";
echo $tip[$week] . "<br>"; // $tip value is subject to $week
//associate array with
$plan["Jan"]="Visit <a
$plan["Feb"]="Visit <a
$plan["Mar"]="Visit <a
$plan["Apr"]="Visit <a
$plan["May"]="Visit <a
$plan["Jun"]="Visit <a
$plan["Jul"]="Visit <a
$plan["Aug"]="Visit <a
$plan["Sep"]="Visit <a
$plan["Oct"]="Visit <a
$plan["Nov"]="Visit <a
$plan["Dec"]="Visit <a

identifier
href=http://www.ibm.com>IBM</a>";
href=http://www.hp.com>HP</a>";
href=http://www.novell.com>Novell</a>";
href=http://www.cnn.com>CNN</a>";
href=http://www.apple.com>Apple</a>";
href=http://www.seagate.com>Seagate</a>";
href=http://www.motorola.com>Motorola</a>";
href=http://www.nokia.com>Nokia</a>";
href=http://www.toshiba.com>Toshiba</a>";
href=http://www.cisco.com>Cisco</a>";
href=http://www.oracle.com>Oracle</a>";
href=http://www.amazon.com>Amazon</a>";

$Mnumber = date("M"); //short text of a month, three letters


echo "The goal for this month is to: $plan[$Mnumber]!<br>";
//associate array with array() function
$class = array(
"Mon"=>"CIS218",
"Tue"=>"CIS184",
"Wed"=>"CIS193",
"Thu"=>"CIS162",
"Fri"=>"CIS246",
"Sat"=>"CIS110",
"Sun"=>"No class!"

PHP

53

);
$w = date("D"); // textual representation of a day, three letters
echo "You need to teach <b>$class[$w]</b> today!<br>";
?>

2.

Test the program with a Apache server (XAMPP). It looks:

3.

Capture a screen shot similar to the above figure and paste it to a Word document named lab4.doc (or
lab4.docx).

Learning Activity #5: Multi-dimensional array and sorting


1. In the X:\xampp\htdocs\myphp directory, use Notepad to create a new file named lab4_5.php with the
following contents:
<?php
$food = array (
"fruits"=>array("banana","apple","orange"),
"nuts"=>array("almond","cashew","peanut"),
"grains"=>array("corn","wheat","oat"),
"seeds"=>array("popcorn","sesame","sunflower")
);
// print unsorted list
print_r($food);
print "<hr>";
// print unsorted list
sort($food);
print_r($food);
print "<hr>";
// print a reversed sorted list
rsort($food);
print_r($food);
print "<hr>";
?>

2.

Test the program with a Apache server (XAMPP). It looks:

PHP

54

3.

Capture a screen shot similar to the above figure and paste it to a Word document named lab4.doc (or
lab4.docx).

Submitting the lab


1. Create a .zip file named lab4.zip containing:
Lab4_1.php
Lab4_2.php
Lab4_3.php
Lab4_4.php
Lab4_5.php
Lab4.doc (or .docx and make sure this file contains all the five screen shots)
2.

Upload the zipped file as response to question 11 or Assignment 4 (available in Blackboard).

PHP

55

Lecture #5:

Selection Structure

Introduction

Any PHP script is built out of a series of statements. A statement can be an assignment, a function call,
a loop (discussed in a later lecture), a conditional statement, or even a statement that does nothing (an
empty statement). Statements usually end with a semicolon. In addition, statements can be grouped
into a statement-group by encapsulating a group of statements with curly braces. A statement-group is
a statement by itself as well.

Control
Statements

A control statement is a statement that is used to alter the continuous sequential invocation of
statements. It is a statement that controls when and how one or more other statements are executed. In
PHP, statements fall into three general types:
Assignment, where values, usually the results of calculations, are stored in variables (as discussed
in previous lecture).
Input / Output, data is read in or printed out.
Control, the program makes a decision about what to do next.
Unless being specified, statements in a PHP program are executed one after another in the order in
which they are written, this is known as sequential execution. However, programs can be much more
useful if the programmer can control the sequence in which statements are run. You will soon find out
that there will always be a need to jump off the linear sequence. A transfer of control occurs when the
next statement to be executed are specified by the programmer, instead of the immediate succeeding
statement.
As a programmer, the control of statement sequence is actually the arrangement of:
selecting between optional sections of a program.
repeating important sections of the program.
All PHP programs are thus written in terms of three forms of control: sequence, selection, and
repetition.

Conditional
Statements

A conditional statement is used to decide whether to do something at a special point or to decide


between two courses of action. A conditional statement chooses among alternative actions in a PHP
program. The if statement performs (selects) an action based on a tested condition. A condition is an
expression with a Boolean value (TRUE or FALSE) that is used for decision making. For example,
$x >= 3

In this statement, the value of variable $x can be anything, such as 1, 2, 8, 110, 224, and so on. This
expression is then sometimes true, sometime false depending on the current value of $x .
Conditional statements can be as simple as the above one or they can be compound statements as
shown below:
($x >= 3) AND ($x <= 15)

For example:
<?php
$s = 6;
$t = 5;
if ($s>4 AND $t>4) {echo "TRUE!"; }
?>

The output is TRUE! because both conditions $s>4 and $t>4 are true.

PHP

56

The if
statement

The if statement is one of the most important features of many languages, PHP included. It allows for
conditional execution of code fragments. PHPs if statement is similar to that of the C programming
language.
In PHP, many conditional statements (also known as selection statements) begin with the keyword if,
followed by a condition in parentheses. The statement(s) of execution are grouped together between
curly brackets { }. Such a grouping is called a compound statement or simply a block. The syntax
then looks like:
if ( condition )
{ execution }

where condition is an expression that is evaluated to its Boolean value. If expression evaluates to
TRUE, PHP will execute the statement, and if it evaluates to FALSE, PHP ignores it.
The following test decides whether a student has passed an exam with a passing mark of 60. Notice
that it is possible to use the if part without the else part.
<?php
$grade=rand(50,99); // generate a random number from 50 to 99
if ($grade >= 60)
// test if the value of user entry >= 60
{ echo Pass!; } // display Pass!
?>

The following example checks whether the current value of the variable $hour is less than 12 and the
echo statement displays its message only if this is the case (namely $hour < 12 is true).
<?php
$hour = date(H); //get the current hour value
if ($hour < 12) {
echo Good morning!;
}
?>

The if ... else statement


The above example has a logic problem. It specifies what to execute when the $grade is greater than or
equal to 60, but it did not specify what to do if the $grade is less than 60. To solve this logic problem,
use the if ... else statement. The if statement performs an indicated action (or sequence of actions) only
when the condition is tested to be true; otherwise the execution is skipped. The if else statement
performs an action if a condition is true and performs a different action if the condition is false.
The else statement extends an if statement to execute a statement in case the expression in the if
statement evaluates to FALSE. The syntax looks like:
if ( condition )
{ execution 1 }
else
{ execution 2 }

// do this when condition is TRUE


// do this when condition is FALSE

You can now rewrite the above example to:


<?php
$grade=rand(50,99); // generate a random number from 50 to 99
if ($grade >= 60) // condition
{ echo Pass!; } // execution 1
else
{ echo Fail!; } // execution 2
?>

PHP

57

The else statement is only executed if the if expression is evaluated to FALSE as well as any elseif
expressions that evaluated to FALSE.
Often you need to have more than one statement to be executed conditionally. Of course, there is no
need to wrap each statement with an if clause. Instead, you can group several statements into a
statement group.
If statements can be nested infinitely within other if statements, which provides you with complete
flexibility for conditional execution of the various parts of your program.
The elseif statement
Sometimes a programmer needs to make a decision based on several conditions. This can be done by
using the elseif variant of the if statement. The elseif statement, as its name suggests, is a combination
of if and else. Like else, it extends an if statement to execute a different statement in case the original if
expression evaluates to FALSE. However, unlike else, it will execute that alternative expression only if
the elseif conditional expression evaluates to TRUE.
As soon as one of these conditions yields a true result, the following statement or block is executed and
no further comparisons are performed.
There may be several elseifs within the same if statement. The first elseif expression (if any) that
evaluates to TRUE would be executed. In PHP, you can also write else if (in two words) and the
behavior would be identical to the one of elseif (in a single word). The syntactic meaning is slightly
different, but the bottom line is that both would result in exactly the same behavior.
The elseif statement is only executed if the preceding if expression and any preceding elseif
expressions evaluated to FALSE, and the current elseif expression evaluated to TRUE.
In the following example we are awarding grades depending on the exam result.
<?php
$grade=rand(50,99); // generate a random number from 50 to 99
if ($grade >= 90)
{ echo A; }
elseif ($grade >= 80)
{ echo B; }
elseif ($grade >= 70)
{ echo C; }
elseif ($grade >= 60)
{ echo D; }
else
{ echo F; }
?>

In this example, all comparisons test a single variable called result. In other cases, each test may
involve a different variable or some combination of tests. The same pattern can be used with more or
fewer elseifs, and the final lone else may be left out. It is up to the programmer to devise the correct
structure for each programming problem.
The if...then statement can also be used to handle HTML form in one single PHP script (a later lecture
will discuss this topic in details). For example:
<?php
if ($_POST) { // if the form is filled out
$x = $_POST["vofx"];
if ($x>=5) { echo "x is greater than or equal to 5!"; }

PHP

58

else { echo "x is less than 5!"; }


}
else { // otherwise display the form
?>
<form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post">
Enter a value for <i>x</i>:
<input type="text" name="vofx" size=5>
<input type="submit" value="Check"></form></p>
<?php
}
?>

The $_POST expression is evaluated when the script is loaded to determine whether or not the form
fields (a textbox) has been filled in. If so, the script ignores the else part and processes the user input. If
not, the script displays only a form for the user to fill in.
if ($_POST) { // if the form is filled out
...... }
else { // otherwise display the form
?>
<form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post">
......
</form>
<?php
}
?>

Notice that it uses the $_SERVER['PHP_SELF'] system variable to send the user inputs to itself.
Alternative
syntax

PHP offers an alternative syntax for some of its control structures. the basic form of the alternate
syntax is to change the opening brace to a colon (:) and the closing brace to endif. For example:
<?php if ($a == 5): ?>
A is equal to 5
<?php endif; ?>

In the above example, the HTML block "A is equal to 5" is nested within an if statement written in the
alternative syntax. The HTML block would be displayed only if $a is equal to 5.
The alternative syntax applies to else and elseif as well. The following is an if structure with elseif and
else in the alternative format.
<?php
if($a > $b):
echo $a." is greater than ".$b;
elseif($a == $b): // Note the combination of the words.
echo $a." equals ".$b;
else:
echo $a." is neither greater than or equal to ".$b;
endif;

PHP

59

?>

Note that elseif and else if will only be considered exactly the same when using curly brackets as in
the above example. When using a colon to define your if/elseif conditions, you must not separate else if
into two words or PHP will fail with a parse error.
Problem of
complexity

When writing a PHP program, you may have to compare the same variable (or expression) with many
different values, and execute a different piece of code depending on which value it equals to. You can
do so with nested if ... else statements, but it will increase the complexity of your program. Consider
the following example:
<?php
$x= date("w"); //number of the day of the week; 0 for Sunday
if ($x == 0) { echo "Sunday"; }
elseif ($x == 1) { echo "Monday"; }
elseif ($x == 2) { echo "Tuesday"; }
elseif ($x == 3) { echo "Wednesday"; }
elseif ($x == 4) { echo "Thursday"; }
elseif ($x == 5) { echo "Friday"; }
elseif ($x == 6) { echo "Saturday"; }
else { echo "No such option!"; }
?>

This above code will display different value according to the number of the weekday0 for Sunday, 1
for Monday, and so on. If the number is not in {0, 1, 2, 3, 4, 5, 6}, then it will display No such
option!. This example use only one block of code to handle 8 conditions, which certainly increase the
complexity (imaging you have 20 conditions!). This is exactly what the switch statement is for.
The
switch..case
Statement

The switch statement is similar to a series of if statements on the same expression, but it is a better way
of writing a program when a series of if..elses occurs. It is important to understand how the switch
statement is executed in order to avoid mistakes. The switch statement executes line by line (actually,
statement by statement). The switch/case statement syntax is as follows:
switch (expression) {
case value1:
statement(s);
break;
case value2:
statement(s);
break;
...........
...........
default:
statement(s);
break;
}

where the case expression may be any expression that evaluates to a simple type, that is, integer or
floating-point numbers and strings. Arrays or objects cannot be used here unless they are not
referenced to a simple type.
In a switch statement, the condition is evaluated only once and the result is compared to each case
statement. In an elseif statement, the condition is evaluated again. If your condition is more
complicated than a simple compare and/or is in a tight loop, a switch may be faster. The advantage of
using switch statement is to simplify the complexity of if...elses.
The following two examples show two different ways to test for the same conditions - one uses a series
of if and elseif statements, and the other uses the switch statement.

PHP

60

if statement

switch statement

<?php
if ($i == 0) {
echo "i equals
} elseif ($i == 1)
echo "i equals
} elseif ($i == 2)
echo "i equals
}
?>

<?php
switch ($i)
case 0:
echo "i
break;
case 1:
echo "i
break;
case 2:
echo "i
break;
}
?>

0";
{
1";
{
2";

{
equals 0";
equals 1";
equals 2";

It is important to understand how the switch statement is executed in order to avoid mistakes. The
switch statement executes line by line (actually, statement by statement). In the beginning, no code is
executed. Only when a case statement is found with a value that matches the value of the switch
expression does PHP begin to execute the statements. PHP continues to execute the statements until
the end of the switch block or the first time it sees a break statement. The break construct is used to
force the switch code to stop. PHP will continue to execute the statements until the end of the switch
block or the first time it sees a break statement. If you dont include a break statement at the end of a
cases statement list, PHP will go on executing the statements of the following case.
Consider the following examples;
<?php
// good code
$x= date("w");

<?php
// bad code
$x= date("w");

switch ($x) {
case 0:
echo "Sunday"; break;
case 1:
echo "Monday"; break;
case 2:
echo "Tuesday"; break;
case 3:
echo "Wednesday"; break;
case 4:
echo "Thursday"; break;
case 5:
echo "Friday"; break;
case 6:
echo "Saturday"; break;
default:
echo "No such weekday"; break;
}
?>

switch ($x) {
case 0:
echo "Sunday";
case 1:
echo "Monday";
case 2:
echo "Tuesday";
case 3:
echo "Wednesday";
case 4:
echo "Thursday";
case 5:
echo "Friday";
case 6:
echo "Saturday";
default:
echo "No such weekday";
}
?>

Only when a case statement is found with a value that matches the value of the switch expression does
PHP begin to execute the switch statements.
Notice that a special case is the default case. This case matches anything that doesnt match any other
cases, and should be the last case statement.
In PHP, the statement list for a case can also be empty, which simply passes control into the statement
list for the next case. The use of default case is also optional. In the following example, only when the
weekday is Tuesday will a user see an output.

PHP

61

<?php
$i= date("w");
switch ($i) {
case 0:
case 1:
case 2:
echo "It is Tuesday, and you just won the prize!";
break;
case 3:
case 4:
case 5:
case 6:
}
?>

In PHP, the switch structure allows usage of strings. For example,


<?php
switch ($i) {
case "apple":
echo "i is apple";
break;
case "bar":
echo "i is bar";
break;
case "cake":
echo "i is cake";
break;
}
?>

The alternative syntax for control structures is supported with switches. For example:
<?php
switch ($i):
case 0:
echo "i equals
break;
case 1:
echo "i equals
break;
case 2:
echo "i equals
break;
default:
echo "i is not
endswitch;
?>

0";
1";
2";
equal to 0, 1 or 2";

It is possible to use a semicolon ( ; )instead of a colon ( : )after a case. For example:


<?php
switch($beer)
{
case 'Tuborg';
case 'Carlsberg';
case 'Heineken';
echo 'Good choice';
break;
default;
echo 'Please make a new selection...';
break;

PHP

62

}
?>

Review
Questions

1. The result of the following calculation is __.


<?php echo (9 != 7); ?>

A. 1
B. 0
C. True
D. False
2. The result of the following calculation is __.
<?php echo !(6 <= 4); ?>

A. 1
B. 0
C. True
D. False
3. Given the following code segment, what is the output?
<?php
$x = 3;
if ($x > 3) { echo "Correct!"; }
else { echo "Incorrect!"; }
?>

A. Correct!
B. Incorrect!
C. True
D. False
4. Given the following code segment, what is the output?
<?php
$x = 6;
if (($x > 3) AND ($x <=7)) { echo "Correct!"; }
else { echo "Incorrect!"; }
?>

A. Correct!
B. Incorrect!
C. True
D. False
5. The result of the following calculation is __.
<?php
$i=6;
if ($i>=4) {
if ($i=5) { echo $i; }
else { echo $i--;}
}
else { echo $i++; }
?>

A. 4
B. 5
PHP

63

C. 6
D. 3
6. The result of the following calculation is __.
<?php
$i=3;
if ($i>=4) {
if ($i=5) { echo $i; }
else { echo $i--; }
}
else { echo ++$i; }
?>

A. 4
B. 5
C. 6
D. 3
7. If the value of $i is 0, what is output?
<?php
switch ($i) {
case 0:
echo "i equals
break;
case 1:
echo "i equals
break;
case 2:
echo "i equals
break;
default:
echo "i equals
break;
}
?>

0";
1";
2";
3";

A. i equals 0
B. i equals 1
C. i equals 2
D. i equals 3
8. If the value of $i is 3, what is output?
<?php
switch ($i) {
case 0:
echo "i equals
break;
case 1:
echo "i equals
break;
case 2:
echo "i equals
break;
default:
echo "i equals
break;
}
?>

PHP

0";
1";
2";
3";

64

A. i equals 0
B. i equals 1
C. i equals 2
D. i equals 3
9. If the value of $i is 7, what is output?
<?php
switch ($i) {
case 0:
echo "i equals
break;
case 1:
echo "i equals
break;
case 2:
echo "i equals
break;
default:
echo "i equals
break;
}
?>

0";
1";
2";
3";

A. i equals 0
B. i equals 1
C. i equals 2
D. i equals 3
10. If the value of $i is 0, what is output?
<?php
switch ($i)
case 0:
case 1:
case 2:
default:
}
?>

{
echo "i equals 0";
echo "i equals 1";
echo "i equals 2";
echo "i equals 3";

A. i equals 0
B. i equals 0i equals 1
C. i equals 0i equals 1i equals 2
D. i equals 0i equals 1i equals 2i equals 3

PHP

65

Lab #5

Selection Structure

Preparation #1: Running the server and create default database


1. Insert the USB that contains XAMPP. Determine the drive name (such as F:\).
2. Change to the X:\xampp\ directory (where X must be the correct drive name) to find the setup_xampp.bat
and then execute it. You should see:
######################################################################
# ApacheFriends XAMPP setup win32 Version
#
#--------------------------------------------------------------------#
# Copyright (C) 2002-2011 Apachefriends 1.7.7
#
#--------------------------------------------------------------------#
# Authors: Kay Vogelgesang (kvo@apachefriends.org)
#
#
Carsten Wiedmann (webmaster@wiedmann-online.de)
#
######################################################################
Do you want to refresh the XAMPP installation?
1) Refresh now!
x) Exit

3.

Press 1 and then [Enter]. If re-configuration succeeds, you should see the following message.
XAMPP is refreshing now...
Refreshing all paths in config files...
Configure XAMPP with awk for Windows_NT
###### Have fun with ApacheFriends XAMPP! ######
Press any key to continue ...

Learning Activity #1: if..then statement


1. In the X:\xampp\htdocs\myphp directory (create the myphp subdirectory if it does not exist), use Notepad
to create a new file named lab5_1.php with the following contents:
<?php
if ($_POST) { // if the form is filled out
$x = $_POST["vofx"];
if ($x>=5) { echo "x is greater than or equal to 5!"; }
else { echo "x is less than 5!"; }
}
else { // otherwise display the form
?>
<form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post">
Enter a value for <i>x</i>:
<input type="text" name="vofx" size=5>
<input type="submit" value="Check"></form></p>
<?php
}
?>

2.

Test the program with a Apache server (XAMPP).

PHP

66

to
3.

Capture a screen shot similar to the above figure and paste it to a Word document named lab5.doc (or
lab5.docx).

Learning Activity #2: if ... then


1. In the X:\xampp\htdocs\myphp directory, use Notepad to create a new file named lab5_2.php with the
following contents:
<html>
<body>
Method 1: if<br>
<?php
// Programmer: Penn Wu
$hour=date("h");
if ($hour == "01")
if ($hour == "02")
if ($hour == "03")
if ($hour == "04")
if ($hour == "05")
if ($hour == "06")
if ($hour == "07")
if ($hour == "08")
if ($hour == "09")
if ($hour == "10")
if ($hour == "11")
if ($hour == "12")
?>

{
{
{
{
{
{
{
{
{
{
{
{

echo
echo
echo
echo
echo
echo
echo
echo
echo
echo
echo
echo

"It's
"It's
"It's
"It's
"It's
"It's
"It's
"It's
"It's
"It's
"It's
"It's

One o'clock now!"; }


Two o'clock now!"; }
Three o'clock now!"; }
Four o'clock now!"; }
Five o'clock now!"; }
Six o'clock now!"; }
Seven o'clock now!"; }
Eight o'clock now!"; }
Nine o'clock now!"; }
Ten o'clock now!"; }
Eleven o'clock now!"; }
Twelve o'clock now!"; }

<p>Method 2: if ... then<br>


<?php
$x= date("w"); //number of the day of the week; 0 for Sunday
if ($x == 0) { echo "Sunday"; }
elseif ($x == 1) { echo "Monday"; }
elseif ($x == 2) { echo "Tuesday"; }
elseif ($x == 3) { echo "Wednesday"; }
elseif ($x == 4) { echo "Thursday"; }
elseif ($x == 5) { echo "Friday"; }
elseif ($x == 6) { echo "Saturday"; }
else { echo "No such option!"; }
?>
</body></html>

2.

Test the program with a Apache server (XAMPP). The output should look like:

PHP

67

3.

Capture a screen shot similar to the above figure and paste it to a Word document named lab5.doc (or
lab5.docx).

Learning Activity #3:


1. In the X:\xampp\htdocs\myphp directory, use Notepad to create a new file named lab5_3.php with the
following contents:
<?php
$hour=date("h");
switch ($hour) {
case "01": echo
case "02": echo
case "03": echo
case "04": echo
case "05": echo
case "06": echo
case "07": echo
case "08": echo
case "09": echo
case "10": echo
case "11": echo
case "12": echo
}

"It's
"It's
"It's
"It's
"It's
"It's
"It's
"It's
"It's
"It's
"It's
"It's

One o'clock now!"; break;


Two o'clock now!"; break;
Three o'clock now!"; break;
Four o'clock now!"; break;
Five o'clock now!"; break;
Six o'clock now!"; break;
Seven o'clock now!"; break;
Eight o'clock now!"; break;
Nine o'clock now!"; break;
Ten o'clock now!"; break;
Eleven o'clock now!"; break;
Twelve o'clock now!"; break;

echo "<hr size=1 width=100%>";


$x= date("w"); //number of the day of the week; 0 for Sunday
switch ($x) {
case 0: echo "Sunday"; break;
case 1: echo "Monday"; break;
case 2: echo "Tuesday"; break;
case 3: echo "Wednesday"; break;
case 4: echo "Thursday"; break;
case 5: echo "Friday"; break;
case 6: echo "Saturday"; break;
default: echo "No such option!"; break;
}
?>

2.

Test the program with a Apache server (XAMPP). The output should look like:

3.

Capture a screen shot similar to the above figure and paste it to a Word document named lab5.doc (or
lab5.docx).

Learning Activity #4:


1. In the X:\xampp\htdocs\myphp directory, use Notepad to create a new file named lab5_4.php with the
following contents:
<html>
<body>

PHP

68

<?php
// Programmer: Penn Wu
if ($_POST) {
$choice=$_POST["myurl"];
switch ($choice) {
case 'A':
echo "The URL is: http://www.ibm.com";
break;
case 'B':
echo "The URL is: http://www.att.com";
break;
case 'C':
echo "The URL is: http://www.cnn.com";
break;
default:
echo "Invalid option!";
break;
}
}
else
{
?>
<form action="<?php echo $_SERVER['PHP_SELF'];?>" method="post">
A. IBM<br>
B. ATT<br>
C. CNN<br>
Enter your choice [A-C]:
<input type=text name="myurl" size=2>
<input type="submit" value="submit">
</form>
<?php
}
?>
</body>
</html>

2.

Test the program with a Apache server (XAMPP). The output should look like:
(Be sure to use capital letters A, B, or C. Its case sensitive!)

3.

Capture a screen shot similar to the above figure and paste it to a Word document named lab5.doc (or
lab5.docx).

Learning Activity #5: switch...case


PHP

69

1.

In the X:\xampp\htdocs\myphp directory, use Notepad to create a new file named lab5_4.php with the following
contents:
<?php
//Chinese Zodiac
if ($_POST) { // if the form is filled out
$y = $_POST["yr"] % 12;
switch ($y) {
case 0:
$z = "Monkey"; break;
case 1:
$z = "Rooster"; break;
case 2:
$z = "Dog"; break;
case 3:
$z = "Pig"; break;
case 4:
$z = "Rat"; break;
case 5:
$z = "Cow"; break;
case 6:
$z = "Tiger"; break;
case 7:
$z = "Rabbit"; break;
case 8:
$z = "Dragon"; break;
case 9:
$z = "Snake"; break;
case 10:
$z = "Horse"; break;
case 11:
$z = "Goat"; break;
}
echo "You were born in a <b>$z</b> year!";
}
else { // otherwise display the form
?>
<form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post">
What year were you born? <i>x</i>:
<input type="text" name="yr" size=5>
<input type="submit" value="Check"></form></p>
<?php
}
?>

2.

Test the program with a Apache server (XAMPP).

PHP

70

to
3.

Capture a screen shot similar to the above figure and paste it to a Word document named lab5.doc (or
lab5.docx).

Submitting the lab


1. Create a .zip file named lab5.zip containing:
Lab5_1.php
Lab5_2.php
Lab5_3.php
Lab5_4.php
Lab5_5.php
Lab5.doc (or .docx and make sure this file contains all the five screen shots)
2.

Upload the zipped file as response to question 11 or Assignment 5 (available in Blackboard).

PHP

71

Lecture #6:

Repetition structure

Introduction

The term repetition structure simply means to repeat or to loop certain pieces of code. Every loop
requires an evaluation or else it will result in an endless loop. At some point the condition must test
false in order to exit the loop.

The for
Loop

When you need to execute a block of code a specific number of times, the for() statement is a good
choice. A for() statement is a looping structure that executes a section of code, then repeats the loop
again until the counter reaches the maximum value. It then exits the loop and continues with the rest
of the script.
In PHP, for() statement use the syntax of:
for( initial value; last value; increment/decrement )
{
PHP codes
}

The initial value of the for() statement variable, is known as the iterator. This variable is used as a
counter for the loop. Consider the following example, where the $i=1 part specifies the initial value
of the variable $i.
<?php
for( $i=1; $i<=4; $i++ )
{
echo $i . "<br>";
}
?>

The last value $i++ defines when the loop should stop. It evaluates the current value of the iterator
every time when a cycle of the loop begins. This occurs at the beginning of each loop. If the
condition evaluates as true (e.g. $i=3), then the loop continues; otherwise the entire code block is
forced to come to an end. Refer to the above example, the value of the variable $i can only be {1, 2,
3, 4}, because 4 is the largest possible value defined by the last value expression, namely $<=4.
The increment/decrement part of expression defines how to increment (or decrement) the value of
the iterator. When the increment operator (++) is used, the value increments by 1. When +=2 is used,
the value increments by 2. Refer to previous lecture for details about increment/decrement operator.
Although the increment operator (++) is frequently used to modify the value of the iterator, it's not
your only option. You can use the decrement operator to count backwards through a loop. For
example:
<?php
for( $i=4; $i >= 0; $i-- )
{
echo $i . "<br>";
}
?>

You are also free to modify the iterator by any increment or decrement value you choose. For
example:
<?php
for( $i=0; $i < 100; $i += 10 )
{
echo $i . "<br>";

PHP

72

}
?>

It is a common practice to iterate though arrays like in the example below.


<?php
$people = Array(
Array('name' => 'Kalle', 'salt' => 856412),
Array('name' => 'Pierre', 'salt' => 215863)
);
for($i = 0; $i < sizeof($people); ++$i)
{
$people[$i]['salt'] = rand(000000, 999999);
}
?>

The problem lies in the second for expression. This code can be slow because it has to calculate the
size of the array on each iteration. Since the size never changes, it can be optimized easily using an
intermediate variable to store the size and use in the loop instead of sizeof. The example below
illustrates this.
<?php
$people = Array(
Array('name' => 'Kalle', 'salt' => 856412),
Array('name' => 'Pierre', 'salt' => 215863)
);
for($i = 0, $size = sizeof($people); $i < $size; ++$i)
{
$people[$i]['salt'] = rand(000000, 999999);
}
?>

PHP also supports the alternate "colon syntax" for the for loops.
for (expr1; expr2; expr3):
statement
...
endfor;

In the beginning of each iteration, expr2 is evaluated. If it evaluates to TRUE, the loop continues and
the nested statement(s) are executed. If it evaluates to FALSE, the execution of the loop ends.
At the end of each iteration, expr3 is evaluated (executed).
Each of the expressions can be empty or contain multiple expressions separated by commas. In
expr2, all expressions separated by a comma are evaluated but the result is taken from the last part.
expr2, being empty, means the loop should be run indefinitely. This may not be as useless as you
might think, since often you'd want to end the loop using a conditional break statement instead of
using the for truth expression.
The foreach
statement

As stated before, the for construct does not support arrays. PHP thus uses the
foreach statement to iterate over arrays. In fact, foreach works ONLY on arrays and
will issue an error when you try to use it on a variable with a different data type or
an uninitialized variable.
In PHP, foreach has two syntaxes;

PHP

73

foreach (array_expression as $VariableName)


PHP statement

and,
foreach (array_expression as $key => $VariableName)
PHP statement

The foreach statement form loops over the array given by array_expression. With
each loop, the value of the current element is assigned to $VariableName and the
internal array pointer is advanced by one. Consider the following example, it uses
foreach to generate HTML hyperlinks, such as <a href="http://www.cnn.com">cnn</a>, in
a loop.
<html><body>
My TV list:<br>
<?php
$site= array("hbo","cnn","cbs","pbs","abc","nbc","fox","tnt","tbs","mtv");
foreach ($site as $url) { //shift values from $site to $url
//this creates hyperlinks
echo "<a href=\"http://www.$url.com\">$url</a>, ";
}
?>
</body></html>

The output is:


My TV list:
hbo, cnn, cbs, pbs, abc, nbc, fox, tnt, tbs, mtv,

You can also re-write the code using the following syntax. They are functionally
identical.
<html><body>
My TV list:<br>
<?php
$site= array("hbo","cnn","cbs","pbs","abc","nbc","fox","tnt","tbs","mtv");
foreach ($site as $key => $url) {
echo "<a href=\"http://www.$url.com\">$url</a>, ";
}
?>
</body></html>

Notice that the second example is a minor but useful extension of the first. You can
also choose one of the demonstrated usages below to cope with any possible
programming need.
<?php
// sample code 1
$a = array(1, 3, 5, 7);

PHP

//output
$a is 1.
$a is 3.
$a is 5.

74

foreach ($a as $v) {


echo "\$a is $v.<br>";
}
?>
<?php
// sample code 2
$a = array(1, 3, 5, 7);

$a is 7.

//output
$a[0] => 1.
$a[1] => 3.
$a[2] => 5.
$a[3] => 7.

$i = 0; // assign initial key to array


foreach ($a as $v) {
echo "\$a[$i] => $v.\n";
$i++;
}
?>

Note: What happens if you assign $i=1;?


<?php
// sample code 3
$a = array(
"one" => 1,
"three" => 3,
"five" => 5,
"seven" => 7
);

//output
$a[one] => 1
$a[three] => 3
$a[five] => 5
$a[seven] => 7

foreach ($a as $k => $v) {


echo "\$a[$k] => $v.\n";
}
?>

You can use the foreach statement through the characters of a string using the
str_split() function. For example:
<?php
$string="string";
$array = str_split($string);
foreach($array as $char) print($char."<br/>");
?>

This output looks like:


s
t
r
i
n
g

The while
loop

The while loop is the simplest type of loop in PHP, but it still needs the three basic component
arguments: initial value, terminal value, and increment (or decrement).
PHP supports two syntax of the while statement. For example:
initial-value;
while (expression) {
statement
...
Increment;

PHP

75

or
while (expression):
statement
...
endwhile;

You can group multiple statements within the same while loop by surrounding a group of statements
with curly braces, or by using the alternate endwhile statement.
Consider the following two codes, they generate identical outputs as shown below.
<?php
$i=0;
while ($i<4) {
echo "$i<br>";
$i++;
}
?>

<?php
$i=0;
while ($i<4)
echo "$i<br>";
$i++;
endwhile;
?>

The $i=0; part assigns the initial value 0 to the variable $i, which means $i starts with a value 0. The
$i<4 expression defines the terminal value, which means $i must be the integer smaller than 4
(namely 3 is the terminal value). Both $i=0 and $i<4 defines a range of possible value {0, 1, 2, 3} to
this while loop.
The while statement tells PHP to execute the nested statement(s) repeatedly, as long as the while
expression evaluates to TRUE. The value of the expression is checked each time at the beginning of
the loop, so even if this value changes during the execution of the nested statement(s), execution will
not stop until the end of the iteration.
The while statement checks if $i is less than 4. If true, it displays the value starting 0. The loop is
forced to stop when $i is equal to (or larger than) 4. The output looks like:
0
1
2
3

The
do..while
Loop

The do...while loop is a variation of while loop, except the truth expression is checked at the end of
each iteration instead of in the beginning.
The main difference from regular while loops is that the first iteration of a dowhile loop is
guaranteed to run, the truth expression is only checked at the end of the iteration, whereas it may not
necessarily run with a regular while loop. The truth expression is checked at the beginning of each
iteration, if it evaluates to FALSE right from the beginning, the loop execution would end
immediately.
There is just one syntax for do-while loops, as illustrated in the following example:
<?php
$i=0;
do {
echo $i . "<br>";
$i++;
}
while ($i < 4 );
?>

PHP

76

Problem of
infinite loop

It is absolutely essential that a for loop be written in such a way that the iterator will eventually
evaluate to false. If not, the for loop will never terminate, and this is called an infinite loop. If your
script appears to hang, check the for loop to make sure this didn't occur. What does an infinite loop
look like? Consider the following example:
<?php
for( $i=0; $i < 10; $i
{
echo $i . "<br>";
}
?>

Note: The increment/decrement expression is incorrect. Because $i is not incremented, the


conditional expression will always evaluate as true, and the loop will never terminate.
In the example below, there's no last value, so it is also an endless loop. If you execute such infinite
loop code, you will encounter a situation called memory overflow. The consequence is possibly the
over use of CPU processing, and slowing down of the computer.
<?php
for( $i=0; ; $i++ )
{
echo $i . "<br>";
}
?>

Advanced
Flow
Control

Flow control means exactly what it sounds like it, controlling the flow of something. When using
flow control for programming, what you are doing is regulating the order in which the code is
executed, how many times it is executed, and if it is executed at all.
PHP provides several constructs for advanced flow control. The two commonly used ones are:
break: used to stop the execution of a loop.
continue: stops processing of code within a loop and skips to the next evaluation of the loop.
The break construct ends execution of the current for, foreach, while, do-while or switch structure. It
accepts an optional numeric argument which tells it how many nested enclosing structures are to be
broken out of. Consider the following example wherethe while loop will stop when $n equals to 6.
<?php
echo "Octal digits are ";
$n = 0;
while ($n <= 9)
{
echo "$n ";
if ($n == 7)
{
break; //force the while loop to stop here
}
$n++;
}
?>

Since the loop is forced to stop at the value 7, 8, and 9 will not be displayed. So the output will be:
Octal digits are 0 1 2 3 4 5 6 7

PHP

77

Another example is:


<?php
$arr = array('Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun');
while (list(, $val) = each($arr)) {
echo "$val, ";
if ($val == 'Fri') {
break;

// for the loop to stop when value is Fri

}
}
?>

The output look (without Sat and Sun):


Mon, Tue, Wed, Thu, Fri

The continue construct is used within looping structures to skip the rest of the current loop iteration
and continues execution at the condition evaluation and then the beginning of the next iteration. You
don't break out of the loop when you use continue, you just skip any code that follows it. Also,
continue skips to the next evaluation of the current loop. In other words, if the loop is nested within
another control structure, continue only affects the loop which contains it.
Notice that continue accepts an optional numeric argument which tells it how many levels of
enclosing loops it should skip to the end of. Compare the following codes and their outputs:
Code

Output

<?php
for ($i=0; $i<5; $i++) {
if ($i == 2) {
continue; }
echo $i . " ";
}
?>
0 1 3 4

<?php
for ($i=0; $i<5; $i++) {
echo $i . " ";
}
?>

0 1 2 3 4

The continue construct instructs the computer to proceed to the next statement only when the value is
2.
Review
Questions

1. Given the following code segment, what is the smallest integer value used in the loop?
for( $i=1; $i<=4; $i++ )

A. 0
B. 1
C. 2
D. 3
2. Given the following code segment, what is the largest integer value used in the loop?
for( $i=1; $i<4; $i++ )

A. 0
B. 1
C. 2
D. 3
3. Given the following code segment, what is the smallest integer value used in the loop?

PHP

78

for( $i=3; $i>=0; $i--)

A. 0
B. 1
C. 2
D. 3
4. Given the following code segment, what is the largest integer value used in the loop?
for( $i=3; $i>=0; $i--)

A. 0
B. 1
C. 2
D. 3
5. What is the result of the following code segment?
<?php
for ($i=0;$i<5;$i++) {
echo $i;
}
?>

A. 01234
B. 012345
C. 1234
D. 12345
6. What is the result of the following code segment?
<?php
for ($i=5;$i>=0;$i-=2) {
echo $i;
}
?>

A. 5310
B. 531
C. 543210
D. 420
7. What is the result of the following code segment?
<?php
$i=5;
while ($i++ <= 9) {
echo $i++ . " ";
}
?>

A. 5 6 7 8 9
B. 6 8
C. 6 8 10
D. 5 7 9
8. What is the result of the following code segment?
<?php

PHP

79

$k =8;
do { echo $k . " ";
} while ($k-- < 5);
?>

A. 8 7 6 5
B. 8 7 6
C. 8 6
D. 8
9. Given the following code segment, the output is __.
<?php
for ($i=0; $i<=5; $i++) {
if ($i == 3) {
break; }
echo $i . " ";
}
?>

A. 0 1 2 3 4 5
B. 0 1 2 4 5
C. 0 1 2
D. 3
10. Use the comma operator to perform the following calculation, the value of cat should be?
<?php
for ($i=0; $i<=5; $i++) {
if ($i == 3) {
continue; }
echo $i . " ";
}
?>

A. 0 1 2 3 4 5
B. 0 1 2 4 5
C. 0 1 2
D. 3

PHP

80

Lab #6

Repetition Structure

Preparation #1: Running the server and create default database


1. Insert the USB that contains XAMPP. Determine the drive name (such as F:\).
2. Change to the X:\xampp\ directory (where X must be the correct drive name) to find the setup_xampp.bat
and then execute it. You should see:
######################################################################
# ApacheFriends XAMPP setup win32 Version
#
#--------------------------------------------------------------------#
# Copyright (C) 2002-2011 Apachefriends 1.7.7
#
#--------------------------------------------------------------------#
# Authors: Kay Vogelgesang (kvo@apachefriends.org)
#
#
Carsten Wiedmann (webmaster@wiedmann-online.de)
#
######################################################################
Do you want to refresh the XAMPP installation?
1) Refresh now!
x) Exit

3.

Press 1 and then [Enter]. If re-configuration succeeds, you should see the following message.
XAMPP is refreshing now...
Refreshing all paths in config files...
Configure XAMPP with awk for Windows_NT
###### Have fun with ApacheFriends XAMPP! ######
Press any key to continue ...

Learning Activity #1: initial value, terminal value, and increment


1. In the X:\xampp\htdocs\myphp directory (create the myphp subdirectory if it does not exist), use Notepad
to create a new file named lab6_1.php with the following contents:
<?php
if ($_POST) {
$begin = $_POST["begin"];
$end = $_POST["end"];
$inct = $_POST["inct"];
for ($i = $begin; $i <= $end; $i+=$inct) {
echo "$i<br />";
}
}
else { // otherwise display the form
?>
<form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post">
Begin number:
<input type="text" name="begin" size=5><br />
End number:
<input type="text" name="end" size=5><br />
Increment by:
<input type="text" name="inct" size=5><br />
<input type="submit" value="Check"></form></p>

PHP

81

<?php
}
?>

2.

Test the program with a Apache server (XAMPP). The output looks like:

to
3.

Capture a screen shot similar to the above figure and paste it to a Word document named lab6.doc (or
lab6.docx).

Learning Activity #2: The for Loop


1. In the X:\xampp\htdocs\myphp directory, use Notepad to create a new file named lab6_2.php with the
following contents:
<html><body>
<!-- for loop -->
<table width="100%" border="0" cellspacing="0">
<caption>Alternating row colors</caption>
<?php
// Programmer: Penn Wu
for ($i = 1; $i <= 10; $i++) {
if ($i % 2) {
$color = 'yellow';
} else {
$color = 'red';
}
?>
<tr>
<td bgcolor="<?php echo $color; ?>"><?php echo $i; ?></td>
</tr>
<?php
}
?>
</table>
<! --Note: This code display different row colors depending on the value of $i. If
$i is not divisible by 2 it prints yellow otherwise it prints red colored rows. -->
<! -- foreach loop -->
</body></html>
2.

Test the program with a Apache server (XAMPP). The output looks like:

PHP

82

3.

Capture a screen shot similar to the above figure and paste it to a Word document named lab6.doc (or
lab6.docx).

Learning Activity #3: The foreach Loop


In the X:\xampp\htdocs\myphp directory, use Notepad to create a new file named lab6_3.php with the following

1.

contents:
<html><body>
Method 1:<br>
<?php
// Programmer: Penn Wu
$blood = array('A', 'B', 'O', 'AB');
foreach ($blood as $type) {
echo "<input type=radio>$type";
}
?>
<p>Method 2:<br>
<! -- advanced foreach

-->

<?php
$a = array("Sociology","Management","Chemistry","Biology");
$i = 0; // assign initial key to array
foreach ($a as $v) {
echo "<input type=radio>$a[$i]";
$i++;
}
?>
</body></html>
2.

Test the program with a Apache server (XAMPP). The output looks like:

Note: The use of PHP to process HTML form will be discussed in later lecture!

PHP

83

3.

Capture a screen shot similar to the above figure and paste it to a Word document named lab6.doc (or
lab6.docx).

Learning Activity #4: do..while loop


1. In the X:\xampp\htdocs\myphp directory, use Notepad to create a new file named lab6_4.php with the
following contents:
<?php
if ($_POST) {
$begin = $_POST["begin"];
$end = $_POST["end"];
$inct = $_POST["inct"];
$i = $begin;
do {
echo $i . "<br>";
$i += $inct;
}
while ($i < $end );
}
else { // otherwise display the form
?>
<form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post">
Begin number:
<input type="text" name="begin" size=5><br />
End number:
<input type="text" name="end" size=5><br />
Increment by:
<input type="text" name="inct" size=5><br />
<input type="submit" value="Check"></form></p>
<?php
}
?>

2.

Test the program with a Apache server (XAMPP). The output looks like:

3.

Capture a screen shot similar to the above figure and paste it to a Word document named lab6.doc (or
lab6.docx).

Learning Activity #5: while


1. In the X:\xampp\htdocs\myphp directory, use Notepad to create a new file named lab6_5.php with the
following contents:
<html>
<body style=font-size:12px>

PHP

84

<!-- while -->


<?php
// Programmer: Penn Wu
$rate=rand(3100,3399)/1000; // use rand() function to generate random number
$loan=1000;
echo "<b>Today's interest rate is $rate%</b>";
?>
<table border=1 cellspacing=0 style=font-size:12px>
<tr><th>Equity Loan</th><th>Annual Interest</th></tr>
<?php
while ($loan <= 10000) {
$interest=$loan * $rate / 100; //formula
echo "<tr><td>$loan</td><td>\$$interest</td></tr>"; // \$ escape sequence
$loan+=1000; // increment by 1000
}
?>
</table>
<hr size=1 width=100%>
<!-- do .. while -->
<b>Current exchange rate is:
1 US$ = <?php $euro=rand(120,129)/100; echo $euro ?> Euro$</b>
<?php
$i=5;
do {
$amount = $i * $euro; // formula
echo "US\$$i = Euro\$$amount<br>"; // \$ escapes sequence
$i++; //increment by 1
}
while ($i < 25)
?>
</body></html>
2.

Test the program with a Apache server (XAMPP). The output looks like:

3.

Capture a screen shot similar to the above figure and paste it to a Word document named lab6.doc (or
lab6.docx).

PHP

85

Submitting the lab


1. Create a .zip file named lab6.zip containing:
Lab6_1.php
Lab6_2.php
Lab6_3.php
Lab6_4.php
Lab6_5.php
Lab6.doc (or .docx and make sure this file contains all the five screen shots)
2.

Upload the zipped file as response to question 11 or Assignment 6 (available in Blackboard).

PHP

86

Lecture #7

Functions

What is a
function?

A function is the capability to perform and complete a given task. For example, a car has functions to
start, accelerate, and stop. Each task, such starting the car, accelerating, and stopping the car, is
performed and completed by a function the car has.
In PHP, a function is a set of code created to perform and complete a particular task, such as
formatting strings, changing letter case from lower to upper case, and displaying contents on the
screen. PHP is a language that comes with hundreds of functions created by programmers who
developed the language. PHP, on the other hand, allow users like you to create your own functions to
support your programs. In other words, PHP supports two kinds of functions:
user-defined functions: any function defined by users using a combination PHP commands and
utilities with correct syntax.
built-in functions: any function provided by the PHP as part of the language utilities. The
http://www.php.net site has a list of PHP built-in function.
A lot of the effort involved in learning about PHP, once you get past the fundamental structures of the
language, is in learning where to find the functions that you want.

Usedefined
PHP
functions

The benefit of creating user-defined function is that they reduce the complexity of your application by
dividing the code into smaller and more manageable parts. They eliminate the need for duplicate code
by gathering it all in one place. They also limit the effects of changes to your program, since you only
need to make specific changes to smaller chunks of code. They promote code reuse, because a
generalized function can be used in more than one script. They make code more readable.
The syntax you need to learn about defining a PHP function is:
function Function_Name( Optional_Parameters )
{
PHP codes
}

Notice that function is a keyword which tells PHP you're defining a function. The function_name is
defined by you and must start with an underscore or a letter. The parentheses are required, even if there
aren't any parameters. If there are multiple parameters, separate them with a comma (,). The function
code is enclosed in curly braces {}. For example:
<?php
function mygreeting() {
echo "How are you doing?";
}
?>

The name of function is mygreeting.


Calling a
function?
What does
it mean?

PHP functions, both built-in and user-defined ones, are not executed untill they are called. Calling a
function simply means to place the function name in an appropriate place to execute it.
The above code, however, will not generate any output because the mygreeting() has not yet been not
called on to perform the function. To call a user-defined function, simply add the function name to the
appropriate place to call the function. Compare the following two examples, which generate the same
output.
<?php
mygreeting(); //call the function

PHP

87

<?php
function mygreeting() {

function mygreeting() {
echo "How are you doing?";
}
?>

echo "How are you doing?";


}
mygreeting(); // call the function
?>

Now, compare the following code, which illustrate how different place will generate different output.
Codes

Outputs

I said "
<?php
mygreeting();
function mygreeting() {
echo "How are you doing?";
}
?>
".
I said "How are you doing?".

I said "
<?php
function mygreeting() {
echo "How are you doing?";
}
?>
".
<?php mygreeting() ?>
I said "". How are you doing?

You can call a function anywhere that you can use an expression.
<?php
/* call user-defined function */
function myCar($make, $model) {
echo "$make $model";
}
mycar("Toyota", "Avalon");
?>

The output looks:


Toyota Avalon

PHP also allows you to call user functions through using two built-in functions: call_user_func() and
call_user_func_array(). A small difference in these two examples is that one has all arguments in an
array parameter the other uses multiple parameters. The call_user_func_array() function is an
advanced function and is beyond the discussion of this course.
<?php
/* call user-defined function with call_user_func() */
function myCar($make, $model) {
echo "$make $model";
}
call_user_func('myCar', "Lexus", "ES330");
?>

The output looks like:


Lexus ES330

User-defined functions with parameters


Notice that in the above two examples, the myCar() function has two variables declared within the
parentheses ($make, $model). PHP functions can be more complex than the above examples. They can
receive variables as input and can return data that can be assigned to another variable. Consider the
following example, which uses a function to create a single row of data in a table and the data to fill
the table is passed to the function using the $var variable.
function mytable($var) {
echo "<table border=0 cellpadding=0 cellspacing=0><tr>";
echo "<td>$var</td>";
echo "</tr></table>";
}

PHP

88

In this case, we would use the function like this:


mytable("This is my row of data");

Functions can receive multiple variables by using a comma delimiter to separate them. For example,
the following code allows the user to change the border, cellpadding, and cellspacing values.
function mytable($var, $border="0", $cellp="0", $cells="0") {
print("<table border=$border cellpadding=$cellp
cellspacing=$cells><tr>");
print("<td>$var</td>");
print("</tr></table>");
}

The mytable() function would then be called like this:


mytable("This is my row of data", 0, 1, 1);

This assigns $border, $cellp, and $cells a default value of 0 so that if only one variable or field is
passed to the function, we have default values for our border, cellpadding, and cellspacing values in the
table. When making a call to mytable(), the string "This is my row of data" is displayed in the table, a
border of 0, and a cellpadding and cellspacing value of 1.
Return values
You can use functions to return data as well as to receive it. A PHP user defined function can return
one value if you use the return statement. Consider a simple function called multnum(), which
multiplies two numbers. It must receive the two numbers as input and will then return the multiplied
result as output.
<?php
function multnum($n1, $n2) {
$result = $n1 * $n2;
return($result); // this returns the value
}
$total = multnum(5,10); // call the function and assign values to
$total
echo $total;
?>

In this case, the value of $total will be 50. The function multiplies the two numbers received as input,
assigns that value to $result, and with the return command makes the return value of the function
equivalent to the value of $result. Notice that return($result); and return $result; yields the same
output, as illustrated below.
Compare the outputs of the following codes, with and without the return statement.
Codes

PHP

<?php
function
multiply($revenue,
$tax) {
$netIncome =
$revenue * (1 $tax/100);
return $netIncome;
}

<?php
function
multiply($revenue,
$tax) {
$netIncome =
$revenue * (1 $tax/100);
return;
}

$myMoney =
multiply(100, 7.25);
echo $myMoney;
?>

$myMoney =
multiply(100, 7.25);
echo $myMoney;
?>

89

<?php
function
multiply($revenue,
$tax) {
$netIncome =
$revenue * (1 $tax/100);
}
$myMoney =
multiply(100,
7.25);
echo $myMoney;
?>

Outputs
Explanations

92.75

return $netIncome; (or


return($netIncome);)
returns the value

nothing

nothing

simply a key return means


"exit without sending a
value back."

The "return" statement


is not in use to return
value to be whatever
variable you use with it

Why using user-defined functions?


The primary advantage of custom functions is reuse. If you don't write functions, you may have to
write the same piece of code numerous times in your application, whether it's within the same PHP file
or in others. Here's a basic look at how you can take advantage of user-defined functions in your own
PHP code.
function welcome() {
echo "Welcome to CIS246!<br>";
}

This function simply prints the text "Welcome to CIS246!" to the Web page. It can be called just like a
regular PHP function over and over again:
function welcome() {
echo "Welcome to CIS246!<br>";
}
welcome() // call the function once
welcome() // call the function again
welcome() // again
welcome() // again
........ // again, again, ......

PHP builtin functions

To call any of the available PHP built-in function, simply write the name of the function with correct
syntax. This lecture use the abs() function to illustrate how you can get help from the official PHP
manual (available at http://www.php.net). The PHP manual provides the following information about
the abs() function.
abs()
abs -- Absolute value
Description
number abs ( mixed number )
Returns the absolute value of number. If the argument number is of type
float, the return type is also float, otherwise it is integer (as float
usually has a bigger value range than integer).
Example 1. abs() example
<?php
$abs = abs(-4.2); // $abs = 4.2; (double/float)
$abs2 = abs(5); // $abs2 = 5; (integer)
$abs3 = abs(-5); // $abs3 = 5; (integer)
?>

The manual clearly explains the functionality of abs(), which is of course returning the absolute value
of a number. The description part usually describes the advanced usage with exceptions if applicable.
The example part gives illustrations on how the abs() function can be used.
You can get a list of all the available PHP built-in functions from http://www.php.net/quickref.php. In
this lecture, we will discuss only some of the common ones to get the concepts across to your mind.

PHP

90

Useful PHP
built-in
functions

The HTTP built-in functions are designed for sending specific HTTP headers and cookie data are
crucial aspects of developing large web-based application in PHP.
The print() and echo() function
These are the two popular built-in constructs (rather than functions) that enable you to display
information on screen (or web page). A construct does not require the use of parentheses around the
argument, but functions do. However, in PHP, you can either use print and echo as constructs or
functions. The decision is completely yours. For example:
print("Welcome to CIS246!");

and
print "Welcome to CIS246!";

generate the same result:


Welcome to CIS246!

Similarly,
echo("Don't chase the rainbow!");

and
echo "Don't chase the rainbow!";

also generate the same result:


Don't chase the rainbow!

Which should you use, print or echo? This is very much a matter of personal preference. As you may
tell, the instructor like echo better. The only reason the instructor has is that echo can take multiple
arguments. In other words, with echo, different portions can be separated by commas. For example:
work
won't work

echo "Taiwan is an island!", "China is a continent!";


print "Taiwan is an island!", "China is a continent!";

The header() function


The header() function outputs an HTTP header string. This function must be placed before any other
data is sent to the browser including HTML tags. In reality, this function is commonly used for
location redirection. For example, the following code redirects a user to www.blackboard.edu
automatically.
<?php
header("Location: http://www.blackboard.edu");
exit; // make sure the code will not continue
?>

The header() function also enables you to output a specific HTTP header string, such as a location
redirection, or in our case, a "401" response code: "Unauthorized". This type of header, combined with
a "WWW-Authenticate" header, will activate an authentication dialog box. For example, the following
code will force the web browser to display an authentication window.
<?php
header('WWW-Authenticate: Basic realm="Private"');
header('HTTP/1.0 401 Unauthorized');
exit; // Use exit to ensure the end of the execution
?>

PHP

91

The mail() function


This function sends an email from your script. The syntax is:
mail(RecipientAddress, Subject, EmailContent,MailHeaders);

For example, the following code will send an email to jane@cal.edu with a subject CIS246, and the
message saying "Hello!". The "From" line is part of the mail headers:
<?php
mail("jane@cal.edu","CIS246","Hello!","From:a@b.com\n");
?>

The include() and require() functions


The include() and require() functions are very similar in terms of functionality. When called, the code
in the included file becomes part of the script calling it. In other words, anything in the included file
can be used in the script calling it. You can access external PHP code files using the include() function.
For example, given 2 files my1.php and my2.php.
my1.php
<?php
echo "Welcome to CIS246!";
?>

my2.php
<html>
<? include("my1.php"); ?>
</html>

In this example, the myfunctions.php file contains PHP code. The include("my1.php"); line of
my2.php includes the PHP code in mysand execute them as they are part of my2.php. The output will
of course be:
Welcome to CIS246!

The my2.php file can be written using the require() function and still yield the same results. For
example:
<html>
<?
require("my1.php");
?>
</html>

Note: require() and include() are identical in every way except how they handle failure. include()
produces a Warning message while require() results in a Fatal Error message. In other words, don't
hesitate to use require(), if you want a missing file to halt processing of the page. The include()
function does not behave this way, the script will continue regardless.
Common
Math
functions

Mathematics is part of everyday life, so PHP has many mathematical functions to make calculation
easier. Notice that these math functions will only handle values within the range of the integer and
float data types. For example, the abs() function returns the absolute value of a number.
<?php
echo abs(5.9) . "<br />";
echo abs(-21) . "<br />";
echo abs(7);
?>

The output looks like:


5.9
21
7

PHP

92

The exp() function returns the value of Ex, where E is Euler's constant (approximately 2.7183) and x is
the number passed to it. Consider the following code:
<?php
echo exp(1) . "<br />";
echo exp(-1) . "<br />";
echo exp(5) . "<br />";
echo exp(10));
?>

The output looks like:


2.718281828459045
0.36787944117144233
148.4131591025766
22026.465794806718

The number_format() function


The number_format() function returns the formatted version of a specified number. The syntax is:
number_format(FloatNumber,Decimals,Dec_Point,Thousands_sep)

Also, this function accepts either one, two or four parameters (not three):
If only one parameter is given, number will be formatted without decimals, but with a comma (",")
between every group of thousands.
If two parameters are given, number will be formatted with decimals with a dot (".") in front, and a
comma (",") between every group of thousands.
If all four parameters are given, number will be formatted with decimals, dec_point instead of a
dot (".") before the decimals and thousands_sep instead of a comma (",") between every group of
thousands.
For example, to return a formatted version of the number 92371257321 with two decimal places and a
common separating each group of thousands, use:
<?php echo number_format("92371257321","2",".",","); ?>

The result is:


92,371,257,321.00

The rand() and srand() functions


The rand() function generates a random value from a specific range of numbers. By default, the range
is 0 and 32767. The syntax is:
rand(min,max);

Notice that the rand() function will always pick a number randomly from the defined number range. If
min is 10 and max 19, then outputs can only be any number in {10, 11, 12, 13, 14, 15, 16, 17, 18, 19}.
In a sense, rand() is not a true random number generator. unless the srand() function is called to seed
the start point.
The srand() function seeds the random number generation function rand so it does not produce the
same sequence of numbers. It is a true random number generator without predefined range of possible
values. The syntax is:
srand(Seed_Value);

where:
PHP

93

Seed_Values is to be defined by the user. Consider the following example.


<?php
echo rand(0,9) . "<br>"; // return a number from 0 to 9 randomly
srand(time());
echo rand();
?>

Obviously the seed has to change every time the program is run. One way to do this is to feed it the
time() function.
Job
controlling
functions

The sleep() and usleep() functions


The sleep() and usleep() functions set a pause (or a delay) at a given point in the execution of PHP
code. The syntax for the sleep() and usleep() functions is:
sleep(seconds);
usleep(microseconds);

The only difference between sleep() and usleep() is that the given wait period for sleep() is in seconds,
while usleep() is in microseconds. A microsecond is one millionth (10-6) of a second. For example:
<?php
sleep(3); // 3 seconds
for ($x=1; $x<=4; $x++) {
echo $x*2 . "<br>";
}
?>

The output looks like this (after 3 seconds):


2
4
6
8

The following example forces the computer to wait 2 seconds before execute the for loop.
<?php
usleep(2000000); // 2 seconds
for ($x=1; $x<=4; $x++) {
echo $x . "<br>";
}
?>

The output looks like this, after 2 seconds,


1
2
3
4

The die() and exit() functions


The die() and exit() functions provide useful control over the execution of PHP codes. They both offer
an escape route for programming errors. They both will output a message and terminate the current
code. Their syntax is:
die("Message");
exit("Message");

For example:

PHP

94

<?php
$_POST[die("Nothing to display!")];
?>

This will just called die() function to output a given message and terminate the code, because the
$_POST[] is not getting any input. The use of $_POST[] will be discussed in the later lecturer.
Similarly, when accessing a database using PHP scripts, you may have to turn the output buffering on.
When sending headers that shouldn't have any data after them, be sure to erase the buffer before
exiting the script! For example:
<?php
ob_clean();
exit(); // you can add some message if you wish
?>

Note: The ob_clean() function cleans (or erases) the output buffer.
Daterelated
functions

The date() function


PHP use the date() function to return the current date and time, as illustrated in the previous lectures.
In fact, it also allows you to format the date and time values. Using it is very simple:
date("formatting option");

There are a whole range of possible formatting options. You can add your own characters inside the
format string too. Here's a list of all the formatting characters.
a
A
B
d
D
F
g
G
h
H
i
I (capital
i)
j
l
(lowercase
'L')
L
m
M
n
r
s
S
t
T
U
w
PHP

"am" or "pm"
"AM" or "PM"
Swatch Internet time
day of the month, 2 digits with leading zeros; i.e. "01" to "31"
day of the week, textual, 3 letters; i.e. "Fri"
month, textual, long; i.e. "January"
hour, 12-hour format without leading zeros; i.e. "1" to "12"
hour, 24-hour format without leading zeros; i.e. "0" to "23"
hour, 12-hour format; i.e. "01" to "12"
hour, 24-hour format; i.e. "00" to "23"
minutes; i.e. "00" to "59"
"1" if Daylight Savings Time, "0" otherwise.
day of the month without leading zeros; i.e. "1" to "31"
day of the week, textual, long; i.e. "Friday"

Boolean for whether it is a leap year; i.e. "0" or "1"


month; i.e. "01" to "12"
month, textual, 3 letters; i.e. "Jan"
month without leading zeros; i.e. "1" to "12"
RFC 822 formatted date; i.e. "Thu, 21 Dec 2000 16:01:07 +0200" (added in PHP
4.0.4)
seconds; i.e. "00" to "59"
English ordinal suffix, textual, 2 characters; i.e. "th", "nd"
number of days in the given month; i.e. "28" to "31"
Time zone setting of this machine; i.e. "MDT"
seconds since the epoch
day of the week, numeric, i.e. "0" (Sunday) to "6" (Saturday)

95

Y
y
z
Z

year, 4 digits; i.e. "1999"


year, 2 digits; i.e. "99"
day of the year; i.e. "0" to "365"
time zone offset in seconds (i.e. "-43200" to "43200"). The offset for timezones west
of UTC is always negative, and for those east of UTC is always positive.

The following example illustrates how the format characters are used to set the date and time format:
<?php
header( 'refresh: 0' ); // force the page to refresh every second
//Handling time
echo "Current time is <h1>" . date("h:i:s A T") . "</h1><br>";
/*1. date in DD-Mon-YYYY format
returns the number of day (0-31), month (first 3 letters), and year
(YYYY) */
echo "Today is <b>" . date("d-M-Y") . "</b><br>";
//2. date in my customized format
echo "<b>" . date("M~~d~~y") . "</b><br>";
//3. using Fri May 21st, 2007 08:11 pm format
echo date("D M d, Y h:i a") . "<br>";
//4. using June 5, 2009 4:17 pm format
echo date("F d, Y g:i a");
?>

The getdate() function


The getdate() function returns an associative array containing the date information of the timestamp or
the current local time, if no timestamp is given. It supports the following elements:
"seconds" - seconds
"minutes" - minutes
"hours" - hours
"mday" - day of the month
"wday" - day of the week, numeric : from 0 as Sunday up to 6 as Saturday
"mon" - month, numeric
"year" - year, numeric
"yday" - day of the year, numeric; i.e. "299"
"weekday" - day of the week, textual, full; i.e. "Friday"
"month" - month, textual, full; i.e. "January"
For example,
<?php
$d = getdate();
$month = $d['month'];
$mday = $d['mday'];
$year = $d['year'];
echo "$month $mday, $year";
?>

will generate an output similar to:


November 21, 2009

PHP

96

Notice the $d = getdate(); part of the code, the variable $d is associated with an array of date/time
values held by the getdate() function.
The time() function
In PHP, the time() function Returns the current time measured in the number of seconds since the Unix
Epoch, a term refers to as the time and date corresponding to 0 in an operating system's clock and
timestamp values. Under most UNIX versions the epoch is 00:00:00 GMT, January 1, 1970 (January 1
1970 00:00:00 GMT). For example:
<?php
echo time();
?>

will generate an output similar to the following which means 1128114520 seconds since 00:00:00
GMT, January 1, 1970:
1128114520

Calendar
functions

The calendar extension presents a series of functions to simplify converting between different calendar
formats. The intermediary or standard it is based on is the Julian Day Count. The Julian Day Count is a
count of days starting from January 1st, 4713 B.C. To convert between calendar systems, you must
first convert to Julian Day Count, then to the calendar system of your choice. Julian Day Count is very
different from the Julian Calendar!
The cal_days_in_month() function
The cal_days_in_month() function returns the number of days in a month for a given year and
calendar. For example:
<?php
$n = cal_days_in_month(CAL_GREGORIAN, 2, 2008); // 31
echo "February of 2008 will have $n days!";
?>

The output is:


February of 2008 will have 29 days!

Other
useful
function

The uniqid() and MD5() function


This function generates a unique identifier. You can also specify a user-defined prefix. The syntax is:
uniqid();

or
uniqid("Prefix");

For example:
<?php
echo uniqid() . "<br>"; // generate a random ID
echo uniqid("<b>Code ID</b>: CIS246-") . "<br>"; // with prefix
?>

The output looks similar to (and it changes every time you execute the code):
43409ce4a94ff
Code ID: CIS246-43409ce4a951f

The MD5() function calculates the MD5 hash of a string and returns that hash. MD5 is a famous
PHP

97

encryption algorithm officially known as MD5 Message-Digest Algorithm. This algorithm takes as
input a message of arbitrary length and produces as output a 128-bit "fingerprint" or "message digest"
of the input.
The MD5 algorithm is intended for digital signature applications, where a large file must be
"compressed" in a secure manner before being encrypted with a private (secret) key under a public-key
cryptosystem such as RSA. The md5() syntax is:
md5("string");

The result is a hash of 32-character hexadecimal number. For example:


<?php echo MD5(uniqid()); ?>

The output is similar to:


4087e76debc0c81ef5862a1bfba61df3

Review
Questions

1. Which can call the function in the following code segment?


<?php
function quiz() {
echo Hi;
}
?>

A. call quiz();
B. quiz();
C. run quiz();
D. function quiz();
2. Given the following code segment, which generates the output 62)?
<?php
function pair($x, $y) {
echo $x, $y ;
}
?>

A. pair 6, 2;
B. pair(6) . pair(2);
C. pair(6), pair(2);
D. pair(6, 2);
3. Given the following code segment, the output is __.
<?php
function s($x, $y) {
echo "$x $y";
}
call_user_func('s', "15", "21");
?>

A. 1521
B. 15 21
C. 21 15
D. 2115
4. Given the following code segment, the output is __.
PHP

98

<?php
function n($x, $y) {
$sum = $x + $y;
return($sum);
}
echo n(3,7);
?>

A. 3 + 7
B. $3 + $7
C. 10
D. $sum
5. Given the following code segment, the output is __.
<?php
echo abs(-2.8);
?>

A. 2.8
B. -2.8
C. abs(-2.8)
D. abs(2.8)
6. Which is the function that can be used to redirect the web browser to another web page?
A. redirect();
B. moveto();
C. changeto();
D. header();
7. The function, rand(1, 6), __.
A. generates a random number from 1 to 6.
B. generates a random number between 1 and 6.
C. display either 1 or 6.
D. None of the above.
8. Which function will output a message and terminate the current code?
A. break() B. end() C. die() D. ob_clean()
9. Which will display the current hour value in 12-hour format without leading zeros?
A. <?php echo date("H"); ?>
B. <?php echo date("h"); ?>
C. <?php echo date("G"); ?>
D. <?php echo date("g"); ?>
10. Given the following code segment, the output is __.
<?php echo number_format("1234567890","3",".",","); ?>

A. 1,234,567,890.000
B. 1,234,567,890.00
C. 123,456,789.000
D. 123,456,789.00

PHP

99

Lab #7

Functions

Preparation #1: Running the server and create default database


1. Insert the USB that contains XAMPP. Determine the drive name (such as F:\).
2. Change to the X:\xampp\ directory (where X must be the correct drive name) to find the setup_xampp.bat
and then execute it. You should see:
######################################################################
# ApacheFriends XAMPP setup win32 Version
#
#--------------------------------------------------------------------#
# Copyright (C) 2002-2011 Apachefriends 1.7.7
#
#--------------------------------------------------------------------#
# Authors: Kay Vogelgesang (kvo@apachefriends.org)
#
#
Carsten Wiedmann (webmaster@wiedmann-online.de)
#
######################################################################
Do you want to refresh the XAMPP installation?
1) Refresh now!
x) Exit

3.

Press 1 and then [Enter]. If re-configuration succeeds, you should see the following message.
XAMPP is refreshing now...
Refreshing all paths in config files...
Configure XAMPP with awk for Windows_NT
###### Have fun with ApacheFriends XAMPP! ######
Press any key to continue ...

Learning Activity #1: Common Built-in functions


1. In the X:\xampp\htdocs\myphp directory (create the myphp subdirectory if it does not exist), use Notepad
to create a new file named lab7_1.php with the following contents:
<?php
//programmer: Penn Wu
header('refresh: 2');

// refresh the page every two seconds

$r=rand(1,6); // random number from 1 to 6


switch($r) {
case 1:
$tip= "Sin(60) is " . sin(60);
break;
case 2:
$tip = "The square root of $r is ". sqrt($r);
break;
case 3:
$tip = "987654321 is formatted to " . number_format('987654321',$r,'.',',');
break;
case 4:
$tip = "Your digital ID is " . uniqid();
break;
case 5:
$tip = "2<sup>$r</sup> is ". pow(2,$r);
break;
case 6:
$tip = "$r in binary format is " . decbin($r);
break;

PHP

100

}
echo $tip;
?>

2.

Test the program with a Apache server (XAMPP). Notice that the page refresh every 2 seconds automatically. It
might looks:

3.

Capture a screen shot similar to the above figure and paste it to a Word document named lab7.doc (or
lab7.docx).

Learning Activity #2: User-defined functions


1. In the X:\xampp\htdocs\myphp directory, use Notepad to create a new file named lab7_2.php with the
following contents (By the way, be sure to compare this code with that of lab5_4):
<?php
//programmer: Penn Wu
if ($_POST) {
function ChineseZodiac($Y) { // create user-defined function with parameter
if ($Y%12==4) {$zodiac="Rat";}
elseif ($Y%12==5) {$zodiac="Cow";}
elseif ($Y%12==6) {$zodiac="Tiger";}
elseif ($Y%12==7) {$zodiac="Rabbit";}
elseif ($Y%12==8) {$zodiac="Dragon";}
elseif ($Y%12==9) {$zodiac="Snake";}
elseif ($Y%12==10) {$zodiac="Horse";}
elseif ($Y%12==11) {$zodiac="Goat";}
elseif ($Y%12==0) {$zodiac="Monkey";}
elseif ($Y%12==1) {$zodiac="Rooster";}
elseif ($Y%12==2) {$zodiac="Dog";}
else {$zodiac="Pig";}
echo "You were born in <b>$zodiac</b> year!";
}
$Y=$_POST['byear'];
ChineseZodiac($Y); // call the function with value entered by user
}
else
{
?>
<form action="<?php echo $_SERVER['PHP_SELF'];?>" method="post">
Enter your birth year: <input type="Text" name="byear" size=4>
<input type="submit" value="Check">
</form>
<?php
}
?>

2.

Test the program with a Apache server (XAMPP). The output looks like:

PHP

101

to
3.

Capture a screen shot similar to the above figure and paste it to a Word document named lab7.doc (or
lab7.docx).

Learning Activity #3: Countdown to Christmas


1. In the X:\xampp\htdocs\myphp directory, use Notepad to create a new file named lab7_3.php with the
following contents:
<?php
/* get the current date for comparison */
$month = date("F"); // gets month in letters
$day = date("j");
$year = date("Y");
echo "<p align=center>Today is $month $day, $year.</p>";
/* set the date of Christmas */
$C_Month = 12; // month
$C_Day = 25; // date
$C_Year = date("Y"); // set the year to be current one
/* counting the days left */
$hours_left = (mktime(0,0,0,$C_Month,$C_Day,$C_Year) - time())/3600;
$days_left = ceil($hours_left/24);

// round to the next integer

// display countdown result


echo "<p align=center>There are <b>$days_left</b> more days to CHRISTMAS.";
echo "<br>($C_Month/$C_Day/$C_Year).</p>";
?>

2.

Test the program with a Apache server (XAMPP). It looks similar to:

3.

Capture a screen shot similar to the above figure and paste it to a Word document named lab7.doc (or
lab7.docx).

Learning Activity #4: PHP Monthly Calendar


PHP

102

1.

In the X:\xampp\htdocs\myphp directory, use Notepad to create a new file named lab7_4.php with the
following contents:
<html>
<style>
td {width:20px}
</style>
<?php
$d=date("j"); // get day of the month without leading zeros (1-31)
$m=date("n"); // get numeric value of a month 1 through 12
$Y=date("Y"); //get 4-digit year value
// determine what weekday the 1st day of month is 0-Sun, 1-Mon,..
$w = date("w", mktime(0, 0, 0, $m, 1, $Y));
// determine the total number of days in that month
$days_of_month = cal_days_in_month(CAL_GREGORIAN, $m, $Y);
$M=date("F"); //get full month literal
?>
<table style="font-size:12px;text-align:center">
<caption><?php echo "$M $Y"; ?>, London</caption>
<tr>
<td>Sun</td>
<td>Mon</td>
<td>Tue</td>
<td>Wed</td>
<td>Thu</td>
<td>Fri</td>
<td>Sat</td>
</tr>
<tr>
<?php
if ($w != 0) {
for ($k=0;$k<$w;$k++) { echo "<td></td>"; }
}
for ($i=1;$i<=$days_of_month;$i++) {
if (($i+$k-1)%7 == 0) { echo "</tr><tr><td>$i</td>";}
elseif ($i==$d) { echo "<td bgcolor=#abcdef><b>$i</b></td>" ; }
else { echo "<td>$i</td>" ; }
}
?>
</tr></table>
</html>

2.

Test the program with a Apache server (XAMPP). The output looks like:

PHP

103

3.

Capture a screen shot similar to the above figure and paste it to a Word document named lab7.doc (or
lab7.docx).

Learning Activity #5:


In the X:\xampp\htdocs\myphp directory, use Notepad to create a new file named lab7_5.php with the following

1.

contents:
<?php
// sqrt() is the Square root function
echo sqrt(9) . "<br>"; // the output is 3
//pow(base, exp) Returns base to the power of exp
echo pow(2, 8) . "<br>"; // 256 (2 to the 8th power)
//sin() is Sine, cos() is Cosine
echo sin(60) . "<br>"; // -0.30481062110222
echo cos(60) . "<br>"; // -0.95241298041516
//bindec() converts binary values to decimal, decbin() vice versa
echo bindec(1101) . "<br>"; // 13
echo decbin(13) . "<br>"; // 1101
//max() finds the highest value, min() finds the lowest
echo max("17","10","14","18","15") . "<br>"; // 18
echo min("17","10","14","18","15") . "<br>"; // 10
// round() rounds up or down mathematically
// ceil() rounds up to the next integer
// floor() rounds down to the previous integer
echo round(2.56) . "<br>"; // result is 3
echo round(1.22) . "<br>"; // result is 1
echo ceil(2.56) . "<br>"; // result is 3
echo ceil(1.22) . "<br>"; // result is 2
echo floor(2.56) . "<br>"; // result is 2
echo floor(1.22) . "<br>"; //result is 1
?>

2.

Test the program with a Apache server (XAMPP). The output looks like:

PHP

104

3.

Capture a screen shot similar to the above figure and paste it to a Word document named lab7.doc (or
lab7.docx).

Submitting the lab


1. Create a .zip file named lab7.zip containing:
Lab7_1.php
Lab7_2.php
Lab7_3.php
Lab7_4.php
Lab7_5.php
Lab7.doc (or .docx and make sure this file contains all the five screen shots)
2.

Upload the zipped file as response to question 11 or Assignment 7 (available in Blackboard).

PHP

105

Lecture #8:

Working With Strings Functions

Introduction

String handling is a major topical area in PHP. There are a huge number of functions available for
string implementation. In order to help you learn about the various things you can do with string
functions, this lecture divides PHP string functions into several more manageable groups listed
below.
Basic functions: Here we will look at the difference between single quotes and double quotes.
We'll also look the heredoc syntax and string concatenation.
Displaying functions: In this section we will examine the three most common methods of
displaying strings - echo, print, and printf.
Formatting functions: Different methods of formatting strings such as changing capitalization,
controlling line breaks, and removing excess white space.
Data implementation: Here we will explore ways to prepare data for display or storage in a
database.
Counting: This section will provide you with ways to count characters in a string, check string
length, and determine the number of words in a string.
Substrings: In this section we will look at techniques for working with substrings. You will
learn how to locate a substring and replace portions of a string.
URLs and Base64: Here we will examine how to deal with URLs and parse them into their
separate parts and also how to encode them properly. We will also see how to prepare binary
data for transmission through email.
Hashing: In this section we will discuss how to use hashing to perform user authentication and
to validate the integrity of data.
String handling in PHP is actually the processing of text (or combination of characters) using builtin text processing facilities (functions) provided by PHP. String functions provide all the
functionalities.
You will experiment with some of the string functions of PHP with some examples. There are
powerful functions like regular expressions to manage complex string handling requirements. We
will discuss some of them here.

How to
process
strings using
string
functions?

There are two ways to process strings with PHP string functions.
variable-oriented. Assign a string value to a variable, and then let the string function process
the variable value. In the following example, the string value "Man are from Mars!\n" is first
assigned to a variable $str, and then processed by the nl2br() function.
variable-less. Simply let the string function process the string. For example, the string "Woman
are from Venus!\n" is directly processed by the nl2br() function.
The nl2br() function will convert the PHP newline escaped characters"\n" to an HTML line break
tag "<br>" or "<br />". Notice that you need to use the browser's View Source to view the generated
HTML output.
<?php
$str="Man are from Mars!\n"; //string held by a variable
echo nl2br($str);
echo nl2br("Woman are from Venus!\n"); //string is not held by any
variable
?>

After executing the code above, use the View Source of web browser to see the result. It should look
like this:
Man are from Mars!<br />
Woman are from Venus!<br />

PHP

106

String
Formatting
Functions

The strtolower() and strtoupper() functions


The strtolower() function will convert any given string to all lowercase characters. This can be
useful when comparing strings to make sure that the cases are the same. For example, given a
variable $str with value of APPLE in upper case, the strtolower() convert will the string value to
lower case.
The strtoupper() function is the complement to the strtolower() function. A given string with a value
"orange" in lower case will be converted by strtoupper() function to upper case.
<?php
$str="APPLE";
echo strtolower($str) . "<br>";
echo strtoupper("orange") . "<br>";
?>

Consequently, the output is:


apple
ORANGE

The ucfirst() and ucwords() function


Any string passed to the ucfirst() function will have the first character capitalized. The ucwords()
function acts very similar to the ucfirst() function, except that the first character of all words in the
string are capitalized. Compare the output of these two functions with exactly the same strings in
lower case.
<?php
echo ucfirst("jennifer likes diamonds!") . "<br>";
echo ucwords("jennifer likes diamonds!") . "<br>";
?>

The output is:


Jennifer likes diamonds!
Jennifer Likes Diamonds!

The strrev() function


This function will reverse a string. For example:
<?php
$str="Do you know Debbie Gibson?";
echo $str; // display the string
echo strrev($str); // reverse and display the string
?>

The output will be:


Do you know Debbie Gibson??nosbiG eibbeD wonk uoy oD

The trim(), chop(), ltrim() and rtrim() functions


Both trim() and chop() functions remove excessive blank spaces from the given string. In the
example below, the $str variable is assigned a string value. There are 5 blank spaces between
[ and "This is a sentence." and there are another 20 blank spaces before ].
<?php
$str="[
This is a sentence.
echo trim($str);

PHP

107

]<br>";

echo chop($str);
?>

These two functions remove blank spaces, and the output will be:
[This is a sentence.]
[This is a sentence.]

Additionally, a blank space at the beginning of a string can be stripped with the ltrim() function.
Similarly, rtrim() is same as ltrim(), except it strips blank spaces from the end of the string. In
reality, the rtrim() function is the same as the chop() function.
The str_pad() function
The str_pad() function pads a string to a certain length with another string. In other words, str_pad()
makes a given string (parameter one) larger by padding additional characters as specified by the user
(parameter two). The str_pad() function syntax is:
str_pad ( string, pad_length, pad_string, pad_type )

You can use STR_PAD_LEFT, STR_PAD_RIGHT, or STR_PAD_BOTH to tell the str_pad()


function to add the added string on the left, the right, or both sides to the specified padding length. If
pad_type is not specified it is assumed to be STR_PAD_RIGHT. For example:
<?php
$str = "Goodbye yesterday!";
echo str_pad($str, 30, '>') . "<br>"; // default is set to the right
echo str_pad($str, 30, '>', STR_PAD_LEFT) . "<br>";
echo str_pad($str, 30, '>', STR_PAD_RIGHT) . "<br>";
echo str_pad($str, 30, '>', STR_PAD_BOTH) . "<br>";
?>

Notice that ">" is the character to be added to the string such that the output looks like:
Goodbye yesterday!>>>>>>>>>>>>
>>>>>>>>>>>>Goodbye yesterday!
Goodbye yesterday!>>>>>>>>>>>>
>>>>>>Goodbye yesterday!>>>>>>

The str_repeat() function


This function will repeat the string the given amount of times. The str_repeat() syntax is:
str_repeat(input, multiplier)

For example, the following code will repeat the string "I Love you!" 100 times.
<?php
echo str_repeat("I love you!<br>", 100);
?>

The wordwrap() function


The wordwrap() function wraps a string to a given number of characters using a string break
character such as "\n" or "<br>". Notice that wordwrap() will automatically wrap at column 75 and
break using '\n' (newline) if width or break are not given. The wordwrap() syntax is:
wordwrap(string, width, break ,cut);

For example:
<?php
$str="Government officials pleaded for international assistance to

PHP

108

help dig survivors from the rubble,


treat them and begin repairing shattered infrastructure after a 7.6magnitude earthquake hit northern
Pakistan, India and parts of Afghanistan. The estimated death toll
has increased to about 22,000 people,
with some sources saying it could go much higher.";
echo wordwrap($str, 30, "<br>");
?>

The maximum length of each line is now set to be 30 characters. Consequently the output in HTML
is:
Government officials pleaded<br>
for international assistance<br>
to help dig survivors from the<br>
rubble, treat them and begin<br>
repairing shattered<br>
infrastructure after a<br>
7.6-magnitude earthquake hit<br>
northern Pakistan, India and<br>
parts of Afghanistan. The<br>
estimated death toll has<br>
increased to about 22,000<br>
people, with some sources<br>
saying it could go much<br>
higher.

The split(), str_split(), and chunk_split()function


The split() function split string into array by regular expression. The syntax for split() is:
split ( pattern, string, limit);

This function returns an array of strings, each of which is a substring of string formed by splitting it
on boundaries formed by the case-sensitive regular expression pattern. If limit is set, the returned
array will contain a maximum of limit elements with the last element containing the whole rest of
string. For example, a telephone number in California has a pattern of "714-856-2218" with the "-"
as delimiter. The split() function will break the telephone number into three substrings, each is a
value of an array $a.
<?php
$str="714-856-2218";
$a = split("-", $str);
echo "Area Code: " . $a[0] . "<br>";
echo "Prefix: " . $a[1] . "<br>";
echo "Circuit No.: " . $a[2] . "<br>";
?>

The output looks like:


Area Code: 714
Prefix: 856
Circuit No.: 2218

The str_split() function convert a string to an array. The syntax for str_split() is:
str_split (string, split_length);

If the optional split_length parameter is specified, the returned array will be broken down into
strings of the specified split_length, otherwise each chunk will be one character in length.

PHP

109

<?php
$str="Garden";
$a = str_split($str); // convert the word "Garden" to an array
for ($i = 0 ; $i < strlen($str) ; $i++) {
echo $a[$i] . "<br>"; // display array value one by one
}
?>

The output will be:


G
a
r
d
e
n

Notice the strlen() function returns the length of the string, and will be discussed later. Consider the
following example:
<?php
$str="Garden";
$a = str_split($str,2); // 2 letter in a chunk
for ($i=0;$i<=2;$i++) {
echo $a[$i] . "<br>"; // display array value one by one
}
?>

The output looks like:


Ga
rd
en

The chunk_split() function splits a string into smaller chunks. The syntax for chunk_split() is:
chunk_split ( string , chunklen, end_format)

The chunk_split() function inserts end_format (defaults to "\r\n") every chunklen characters
(defaults to 76). The chunk_split() function returns a new string leaving the original string
untouched. For example:
<?php
$str="Takemeouttotheballgamenow";
echo "<tt>";
echo chunk_split($str, 5, "<br>");
echo "</tt>";
?>

The output looks:


Takem
eoutt
otheb
allga
menow

Displaying
Strings

PHP

The echo(), print(), printf(), and sprintf() functions


The previous lectures used echo() and print() functions frequently. The echo() function displays an
expression, or a list of expressions separated by commas, without blank space. The print() function
displays text as the echo() function does, but each comma inserts a blank space and a line feed is

110

added to the end of the text. Refer to the previous lecture to refresh your memory about the
difference of print() and echo() functions.
The printf() function is intended for printing formatted data. It may be used, for example, to print
out a data type of double with two-digit precision, or any other case where you might need to
change the format of your output before displaying it.
<?php
//M_E is the PHP constant of natural logarithm
print (M_E . "<br>"); // without format
printf ("%.2f<br>", M_E); // allow 2 digits after decimal point
printf ("%.3f<br>", M_E); // allow 3 digits after decimal point
printf ("%.4f<br>", M_E); // allow 4 digits after decimal point
?>

Notice that M_E is one of PHP Math constants which are always available as part of the PHP core.
You can visit http://php.net/manual/en/math.constants.php for a list of available PHP
Math constant. The syntax of printf() is:
print (format [, rags])
sprint (format [, rags])

where format is composed of zero or more directives and conversion specifications. A directive is
a PHP built-in instruction to the script interpreter about how to perform a specific task. Conversion
specifications are symbols that specifies the type of the given string and how it is to be formatted,
namely they controls the expression of strings.
Each conversion specification consists of a percent sign (%), followed by one or more of the
following specifiers.
% : A literal percent character. No argument is required.
b : The argument is treated as an integer and presented as a binary number.
c : The argument is treated as an integer and presented as the character with that ASCII value.
d : The argument is treated as an integer and presented as a (signed) decimal number.
u : The argument is treated as an integer and presented as an unsigned decimal number.
f : The argument is treated as a float and presented as a floating-point number.
- : The argument is treated as an integer and presented as an octal number.
s : The argument is treated as and presented as a string.
x : The argument is treated as an integer and presented as a hexadecimal number (with
lowercase letters).
X : The argument is treated as an integer and presented as a hexadecimal number (with
uppercase letters).
Consider the following example:
<?php
$n=15;
printf("%b<br>", $n);
printf("%f<br>", $n);
printf("%x<br>", $n);
?>

// result is 1111 (15 in binary)


// result is 15.000000 (floating point)
// result is f (15 in hexadecimal)

Similar to printf(), the sprintf() function returns a string produced according to the formatting string
format. Notice that the function, sprintf(), alone does not display any output.
<?php
$str = 75149682000;
echo sprintf("%.2e<br>", $str); // outputs 7.5e+10

PHP

111

echo sprintf("%.3e<br>", $str); // outputs 7.51e+10


echo sprintf("%.4e<br>", $str); // outputs 7.515e+10
?>

The print_r() function


This function is used to print elements in an array with their keys and values. Keys are surrounded
by braces. For example:
<?php
$a = array('a','p','p','l','e');
print_r($a);
?>

will return:
Array ( [0] => a [1] => p [2] => p [3] => l [4] => e )

Data
implementati
on functions

The addslashes() and stripslashes() functions


This function adds a backslash before a single quote ('), double quote ("), backslash (\), and NUL
(the NULL byte). For example:
<?php
$str = "Don't you know it's ten o'clock now?";
echo addslashes($str);
?>

The output looks like:


Don\'t you know it\'s ten o\'clock now?

The stripslashes() function is the reversed function of addslashes(). With this function, we can undo
what was done with the addslashes() function. For example:
<?php
$str = "Don\'t you know it\'s ten o\'clock now?";
echo stripslashes($str);
?>

will convert the string to:


Don't you know it's ten o'clock now?

The strip_tags(string) function


The strip_tags() function removes HTML and PHP tags from a given string. When we have data
from an unknown source, it is helpful to remove any HTML and PHP tags. The syntax for the
strip_tags() function is:
strip_tags( string, allowed_tags );

In the following example, the <b>...</b> tags are allowed, while <u>...</u> tags are not allowed.
The strip_tag() function will remove the <u>...</u> tags from the string.
<?php
$str = "<u>This is a <b>sentence</b>.</u>";
echo $str . "<br>"; // display unstripped string
echo strip_tags($str,"<b>") . "<br>"; //display stripped string
?>

The output looks like:

PHP

112

This is a sentence.
This is a sentence.

The htmlentities() function


The htmlentities() function converts all applicable characters to HTML entities. With this function
we can change the characters used by the tags to their HTML entity equivalents. This function will
change any character that has a HTML entity equivalent into that entity. The syntax for the
htmlentities() function is:
htmlentities ( string, quote_style, charset);

Available quote_style constants are:


ENT_COMPAT converts double-quotes and leave single-quotes alone.
ENT_QUOTES converts both double and single quotes.
ENT_NOQUOTES leaves both double and single quotes unconverted.
For example:
<?php
$str = "Show me < > in HTML code.";
echo htmlentities($str);
?>

The output looks like:


Show me &lt; &gt; in HTML code.

However, your web browser will automatically convert &lt; and &gt; back to < and >. Be sure to
use use your browsers View Source to view the generated output.
Note: The htmlentities() function is identical to htmlspecialchars() in many ways, except that all
characters which have HTML character entity equivalents are translated into these entities.
Counting

The count() and count_chars() functions


The count() function count elements in an array or properties in an object. Typically, this function is
used to count the number of elements in an array, since anything else will have one element. For
example:
<?php
$make = array("Toyota","Nissan","Mazada","Suzuki","Lexus","Acura");
echo count($make); // output is 6
?>

The count_chars() function enables us to count the frequency of characters in a string. It offers
several different methods of returning the results. For example:
<?php
$str="Do you like PHP?";
$a = count_chars($str,1);
print_r($a);
?>

The output is:


Array ( [32] => 3 [63] => 1 [68] => 1 [72] => 1 [80] => 2 [101] => 1
[105] => 1 [107] => 1 [108] => 1 [111] => 2 [117] => 1 [121] => 1 )

How do you interpret the output [32] => 3? In this case, ASCII codes are used for the numbers
inside the square brackets (the array key) and the frequencies of each letter are used as the other
PHP

113

numbers (the array values).


Common ASCII codes and corresponding characters
32
48
0
64
@
80
P
96
`
112
p

33
!
49
1
65
A
81
Q
97
a
113
q

34
"
50
2
66
B
82
R
98
b
114
r

35
#
51
3
67
C
83
S
99
c
115
s

36
$
52
4
68
D
84
T
100
d
116
t

37
%
53
5
69
E
85
U
101
e
117
u

38
&
54
6
70
F
86
V
102
f
118
v

39
'
55
7
71
G
87
W
103
g
119
w

40
(
56
8
72
H
88
X
104
h
120
x

41
)
57
9
73
I
89
Y
105
i
121
y

42
*
58
:
74
J
90
Z
106
j
122
z

43
+
59
;
75
K
91
[
107
k
123
{

44
,
60
<
76
L
92
\
108
l
124
|

45
61
=
77
M
93
]
109
m
125
}

46
.
62
>
78
N
94
^
110
n
126
~

47
/
63
?
79
O
95
_
111
o
127

Check the above ASCII code table, and you will find that:
32 represents a blank character, -,
68 represents D,
63 represents ?,
72 represents H,
80 represents P,
101 represents e,
105 represents i,
107 represents k,
108 represents l,
111 represents o
117 represents u, and
121 represents y.
Recall that the variable $str holds a string Do you like PHP?, and the string contains 3 blank
spaces, 1 D, 1 ?, 1 H, 2 P's, and so on. The counting results match the frequency of each letter
appears in the string.
The strlen(string) function
The strlen() function returns the length of the given string including the blank space in the string.
This is a basic function that simply returns the length of a string. For example:
<?php
echo strlen("Bonus Miles Eligibility"); // result is 23
?>

Notice that the string "Bonus Miles Eligibility" has 23 characters. Each blank space is counted as a
character also.
The str_word_count(string) function
The str_word_count() function counts the number of words inside string. The syntax for the
str_word_count() function is:
str_word_count ( string, format, char_list);

If the optional format is not specified, then the return value will be an integer representing the
number of words found. In the event the format is specified, the return value will be an array,
content of which is dependent on the format. Common formats are:
1 - returns an array containing all the words found inside the string.
2 - returns an associative array, where the key is the numeric position of the word inside the
string and the value is the actual word itself.
char_list is a list of additional characters which will be considered as 'word'. In the following
example,
PHP

114

<?php
$str="Value Pack ... So you can really
echo str_word_count($str) . "<br>"; //
print_r(str_word_count($str, 1)); echo
print_r(str_word_count($str, 2)); echo
?>

save!";
return 7
"<br>";
"<br>";

the outputs are:


7
Array ( [0] => Value [1] => Pack [2] => So [3] => you [4] => can [5]
=> really [6] => save )
Array ( [0] => Value [6] => Pack [15] => So [18] => you [22] => can
[26] => really [33] => save )

Substrings

The substr() function


The substr() function returns the portion of string specified by the start and length parameters. The
syntax is:
substr ( string, start, length );

If start is non-negative, the returned string will start at the starts position in string, counting from
zero. For instance, in the string 'flower', the character at position 0 is 'f', the character at position 2 is
'o', and so forth. For example:
<?php
echo
echo
echo
echo
echo
?>

substr('flower',
substr('flower',
substr('flower',
substr('flower',
substr('flower',

1) . "<br>"; //
1, 3) . "<br>";
0, 4) . "<br>";
0, 8) . "<br>";
-1, 1) . "<br>";

lower
// low
// flow
// flower
// r

The substr_count() function


This function allows us to count the number of times a substring occurs within a string. The
substr_count() function returns the number of times the needle substring occurs in the haystack
string. The substr_count() function syntax is:
substr_count ( string haystack, string needle, offset, length);

haystack is the string to search in. needle is the substring to search for. Please note that needle is
case sensitive. offset is the offset where to start counting. length is the maximum length after the
specified offset to search for the substring.
In the following example, the word dog appears twice, so the output is 2.
<?php
$text = "A dog chases another dog!";
echo substr_count($text, "dog"); // return 2
?>

The str_replace() and substr_replace() functions


The str_replace() function replaces all occurrences of the search string with the replacement string.
This function returns a string or an array with all occurrences of search in subject replaced with the
given replace value.
In the following example, each occurrence of the word "cat" in the string will be replaced by "dog".
<?php

PHP

115

$str="A cat is not a cat if you think a cat is not a cat!";


echo str_replace("cat", "dog", $str);
?>

The output is then,


A dog is not a dog if you think a dog is not a dog!

The substr_replace() function is used to replace part of a string with another. The syntax is:
substr_replace(string, replacement, start, length);

The substring to be replaced is specified as a range using the start and length arguments. The string
to replace this range of characters is specified with the replacement argument.
The substr_replace() only operates in a left-to-right fashion. If start is a negative value and
length is less than or equal to start, length is considered as having a value of 0 instead. For
example:
<?php
$str="We are students!";
// replace the first two letter with You
echo substr_replace($str, "You", 0, 2) . "<br>";
// replace the last letter with 10 characters
echo substr_replace($str, " and teachers!", -1, 10) . "<br>"; /
?>

The output is:


You are students!
We are students and teachers!

This is a different method of replacing portions of a string based on positions rather than searching
for a substring.
The strstr(), strrchr(), strpos(), and strrpos() functions
The strstr() function finds the first occurrence of a string and display the portion after the first
occurrence. For example:
<?php
$str = "US$5.06";
echo strstr($str, "$");
?>

The output is $5.06.


The strrchr() function finds the last occurrence of a character in a string. For example:
<?php
$ssn = "653-21-7493";
$ssn = strrchr($ssn, "-");
echo "The last 4 digits of your SSN is " . $ssn;
?>

The output looks like:


The last 4 digits of your SSN is -7493

You can use trim() function to strip the unwanted -. For example:
PHP

116

<?php
$ssn = "653-21-7493";
$ssn = trim(strrchr($ssn, "-"),"-");
echo "The last 4 digits of your SSN is " . $ssn;
?>

The output then changes to:


The last 4 digits of your SSN is 7493

The strpos() function finds the numeric position, starting with zero, of first occurrence of a string.
For example, & is the 19th character in a string.
<?php
$str = "http://www.idf.edu&uid=jsmith+psd=p10sf";
echo strpos($str,"&"); // returns 18
?>

The strpos() function is similar to the strstr() function, with the difference being that an integer
specifying where the first occurrence begins is returned rather than a string.
The strrpos() function finds the numeric position, starting with zero, of the last occurrence of a
string. For example, X appears twice in the string, but the X occurrence happens in the place of 17th
character.
<?php
$str = "jmith:X:101:101:X:/usr/jsmith";
echo strrpos($str,"X"); // returns 16
?>

16 is the integer specifying where the last occurrence of a character is found within a string is
returned by this function.
The strspn() and strcspn() function
The strspn() function returns the length of the substring at the start of string that contains only
characters from mask . In the following example, "ABCDE" is the mask. The array $a contains
many strings, each string will be tested by the strspn() function. The name will be returned only
when the initial letter is A, B, C, D, or E.
<?php
$a = array("Mary", "Helen", "Annie", "Jane");
foreach($a as $girl) {
if (strspn($girl, "ABCDE")) {
echo $girl, "<br>";
}
}
?>

Only the name Annie matches with the criteria. This function will return the number of sequential
characters at the beginning of a string that match the characters supplied in the second parameter.
The strcspn() function is opposite to strspn(). Rather than providing the number of characters that
match the second parameter, this function returns the number of sequential characters that do not
match. The name will be returned only when the initial letter is NOT A, B, C, D, or E.
<?php
$a = array("Mary", "Helen", "Annie", "Jane");
foreach($a as $girl) {
if (strcspn($girl, "ABCDE")) {

PHP

117

echo $girl, "<br>";


}
}
?>

The output is then:


Mary
Helen
Jane

URLs and
Base64

The parse_url(url) function


The parse_url() function returns an associative array containing any of the various components of
the URL that are present. If one of URL components is missing, then no entry will be created for it.
The components are:
scheme (protocl) - e.g. http, ftp
host - domain name and domain type
port - TCP/IP port number
user (userID)
pass (password)
path - virtual directory
query - after the question mark ?
fragment - after the hashmark #
This function is not meant to validate the given URL, it only breaks it up into the above listed parts.
Partial URLs are also accepted, parse_url() tries its best to parse them correctly. Using this function,
we can break a URL down into its individual components. For example:
<?php
$str = "http://www.google.com/search?hl=en&q=parse_url";
print_r(parse_url($str));
?>

The output looks like:


Array ( [scheme] => http [host] => www.google.com [path] => /search
[query] => hl=en&q=tokyo+city+tour )

The urlencode() and urldecode() functions


The urlencode() function returns a string in which all non-alphanumeric characters (except -, _,
and .) have been replaced with a percent (%) sign followed by two hex digits and spaces encoded
as plus (+) signs.
It is encoded the same way that the posted data from a WWW form is encoded, that is the same way
as in application/x-www-form-urlencoded media type. This function will convert applicable nonalphanumeric characters into a format acceptable for passing the data through a URL. For example:
<?php
$str = "ftp://jlo@ftp.idf.gov";
echo urlencode($str);
?>

will return:
ftp%3A%2F%2Fjlo%40ftp.idf.gov

The urldecode() function is opposite to the urlencode() function. Any encoding done with urlencode
can be reversed with this function. For example:
PHP

118

<?php
$str = "ftp%3A%2F%2Fjlo%40ftp.idf.gov";
echo urldecode($str);
?>

will return:
ftp://jlo@ftp.idf.gov

The base64_encode() and base64_decode() functions


The base64_encode() function returns data encoded with base64. This encoding is designed to make
binary data survive transport through transport layers that are not 8-bit clean, such as the body
content of a mail .
This function is commonly used for preparing binary data for transmission in an email, because
Base64-encoded data takes about 33% more space than the original data.
<?php
$str = "Santa Claus is coming to town.";
echo base64_encode($str);
?>

This example will produce:


U2FudGEgQ2xhdXMgaXMgY29taW5nIHRvIHRvd24u

The base64_decode() function decodes encoded_data and returns the original data or FALSE on
failure. The returned data may be binary. This function is commonly used for preparing binary data
for transmission in an email, because Base64-encoded data takes about 33% more space than the
original data.
<?php
$str = "U2FudGEgQ2xhdXMgaXMgY29taW5nIHRvIHRvd24u";
echo base64_decode($str);
?>

This example will produce:


Santa Claus is coming to town.

Hashing

The md5 () and md5_file() function


The md5() function calculates the md5 hash of a string. It generates a 32 character hexadecimal
number as specified by the RSA's MD5 Message-Digest Algorithm. It accepts a string of data as its
only parameter. This function has been discussed in the previous lecture.
A hash value (or simply hash), also called a message digest, is a number generated from a string of
text. The hash value is substantially smaller than the text itself, and is generated by a formula in
such a way that it is extremely unlikely that some other text will produce the same hash value.
Use the following example to refresh your memory about the md5().
<?php
$str= "I have a secrete.";
echo "Plaintext : $string",
"MD5 hashed cipher: ", md5($str);
?>

The output looks like:


Plaintext : I have a secrete.

PHP

119

MD5 hashed cipher: 230ebf2fc1da109ddc18ccd3a6bbde5b

This md5_file() function generates the same type of hash as the md5() function, but instead of a
string of data, it accepts a filename contained in a string. This md5_file function calculates the md5
hash value of a given file. It calculates the MD5 hash value of the file specified by the filename
parameter using the RSA Data Security, Inc. MD5 Message-Digest Algorithm, and returns that
hash. The hash is a 32-character hexadecimal number.
The following example creates an MD5 hash for the c5.htm file.
<?php
$file = "c5.htm";
$md5 = md5_file($file);
echo "MD5 hash of this file is ".$md5."";
echo "<p><a href=".$file.">Download this file!</a></p>";
?>

The sha1 (string) function


A 40 character hexadecimal hash as produced by the US Secure Hash Algorithm 1 is returned by
this function. It accepts a string as its only parameter. The sha1() function calculates the sha1 hash
value of a string using the US Secure Hash Algorithm 1, and returns that hash. The hash is a 40character hexadecimal number. For example:
<?php
$str = "Talking about security!";
echo sha1($str);
?>

The output looks like:


61671307f034f83b2ad74b80a31f477beab12f7f

The explode() and implode() functions


The explode() function convert a given string into arrays using a user-defined delimiter character. A
delimiter character may be a space, tab, or symbols like #, ~, | and so on. In the following example,
$str1 and $str2 are two given strings with comma as delimiter. The explode() function converts them
into two arrays: $row1 and $row2.
<?php
$str1="First,Last,School,Major,SSN";
$str2="Jennifer,Lopez,Cypress,CIS,512-69-8124";
$row1 = explode(",", $str1); // comma is delimiter
$row2 = explode(",", $str2);
for ($i=0;$i
echo "$row1[$i] : $row2[$i]<br>";
}
?>

The output is then:


First: Jennifer
Last: Lopez
School: Cypress
Major: CIS
SSN: 512-69-8124

Reverse to explode() function, the implode() function converts a given array into a string by
inserting a user-defined delimiter between any two values of the array.

PHP

120

In the following example, $arr is a given array with four values. The implode() function converts
them into strings by adding </td><td> as delimiters such that each array values will be put in an
HTML table cell.
<?php
$arr = array("PartNo","Description","Qty","UnitPrice");
$str = implode("</td><td>",$arr);
echo "<table width=300 border=1><tr><td>";
echo $str;
echo "</td></tr></table>";
?>

The above code generates the following HTML code as a string:


<table width=300
border=1><tr><td>PartNo</td><td>Description</td><td>Qty</td><td>Unit
Price</td></tr></table>

Consequently, the result displayed on a web browser will be (with HTML table):
PartNo

Review
Questions

Description

Qty

UnitPrice

1. Given the following code segment, which is the correct output?


<?php
echo nl2br("PHP\n Programming!\n");
?>

A. PHP<br /> Programming!<br />


B. PHP\n Programming!\n
C. PHP<br />\n Programming!<br />\n
D. "PHP\n Programming!\n"
2. Given the following code segment, which is the correct output?
<?php
echo strtolower("PHP Programming!\n");
?>

A. PHP Programming!\n
B. "PHP Programming!\n"
C. php programming!
D. PHP PROGRMMING!
3. Given the following code segment, which is the correct output?
<?php
echo str_repeat("PHP", 3);
?>

A. PHP, 3
B. PHPPHPPHP
C. PHP, PHP, PHP
D. "PHP" "PHP" "PHP"
4. Let $str represent a long paragraph, which can set the maximum length of each line to 45
characters?
A. maxlegnth($str, 45, "<br>");
PHP

121

B. wrap($str, 45, "<br>");


C. wordwrap($str, 45, "<br>");
D. line($str, 45, "<br>");
5. Given the following code segment, which is the correct output?
<?php
$str="tomorrow";
$a = str_split($str, 2);
foreach ($a as $str) {
echo $str[$a] . "-";
}
?>

A. o-o-r-wB. to-mo-rr-ow
C. to-mo-rr-owD. t-m-r-o6. Given the following code segment, which is the correct output?
<?php
printf("%b", 15);
?>

A. 15
B. 1155
C. 0105
D. 1111
7. Which function returns the length of a given string including the blank space in the string.
A. str_length();
B. str_count();
C. str_wor_count();
D. strlen();
8. Given the following code segment, which is the correct output?
<?php
$str="Visual PHP Programming!";
echo str_replace("Visual", "", $str);
?>

A. "" PHP Programming!


B. PHP Programming!
C. Visual "" PHP Programming!
D. PHP Visual Programming!
9. Which function finds the numeric position starting with zero?
A. strstr()
B. strpos()
C. strspn()
D. strcspn()
10. Given the following code segment, which is the correct output?
<?php
echo base64_encode("apple");
?>

PHP

122

A. c2FtYmE=
B. b3Jhbmdl
C. YXBwbGU=
D. a2Vpa28=

PHP

123

Lab #8

String Functions

Preparation #1: Running the server and create default database


1. Insert the USB that contains XAMPP. Determine the drive name (such as F:\).
2. Change to the X:\xampp\ directory (where X must be the correct drive name) to find the setup_xampp.bat
and then execute it. You should see:
######################################################################
# ApacheFriends XAMPP setup win32 Version
#
#--------------------------------------------------------------------#
# Copyright (C) 2002-2011 Apachefriends 1.7.7
#
#--------------------------------------------------------------------#
# Authors: Kay Vogelgesang (kvo@apachefriends.org)
#
#
Carsten Wiedmann (webmaster@wiedmann-online.de)
#
######################################################################
Do you want to refresh the XAMPP installation?
1) Refresh now!
x) Exit

3.

Press 1 and then [Enter]. If re-configuration succeeds, you should see the following message.
XAMPP is refreshing now...
Refreshing all paths in config files...
Configure XAMPP with awk for Windows_NT
###### Have fun with ApacheFriends XAMPP! ######
Press any key to continue ...

Learning Activity #1: Home Made Encryption


1. In the X:\xampp\htdocs\myphp directory (create the myphp subdirectory if it does not exist), use Notepad
to create a new file named lab8_1.php with the following contents:
<?php
// a home-made encryption and decryption tool part I - encryption
if ($_POST)
{
$str = $_POST["original"];
$str = urlencode($str);
$str = strrev($str);
$str = base64_encode($str);
echo "Copy and paste the following encrypted cipher to 6_2.php";
echo "<p>Cipher:<br><textarea rows=15 cols=90% name=\"cipher\">";
echo $str;
echo "</textarea></p>";
echo "<a href=\"lab8_2.php\">Go to lab8_2.php</a>";
}
else
{
?>
<form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post">
<p>Enter some message to the text box.</p>
<p>Original:<br>
<textarea rows=15 cols=90% name="original"></textarea>
<input type="submit" value="Encrypt"></form></p>

PHP

124

<?php
}
?>

2.

Test the script after you complete the very next learning activity.

3.

Capture a screen shot similar to the above figure and paste it to a Word document named lab8.doc (or
lab8.docx).

Learning Activity #2: Decryption


1. In the X:\xampp\htdocs\myphp directory, use Notepad to create a new file named lab8_2.php with the
following contents:
<?php
// a home-made encryption and decryption tool Part II - Decryption
if ($_POST)
{
$str = $_POST["cipher"];
$str = base64_decode($str);
$str = strrev($str);
$str = urldecode($str);
echo
echo
echo
echo
echo
}
else
{
?>

"Compare the following decrypted message. Are they correct?";


"<p>Decipher:<br><textarea rows=15 cols=90% name=\"decipher\">";
$str;
"</textarea></p>";
"<a href=\"lab8_1.php\">Return to lab8_1.php</a>";

<form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post">


<p>Enter some message to the text box.</p>

PHP

125

<p>Original:<br>
<textarea rows=15 cols=90% name="cipher"></textarea>
<input type="submit" value="Dencrypt"></form></p>
<?php
}
?>

2.

Test the program with a Apache server (XAMPP) The input and output should look like:

3.

Capture a screen shot similar to the above figure and paste it to a Word document named lab8.doc (or
lab8.docx).

Learning Activity #3:


1. In the X:\xampp\htdocs\myphp directory, use Notepad to create a new file named lab8_3.php with the
following contents:
<html>
<body>
<table border=1 cellspacing=0 cellpadding=2 align="center" style="fontsize:12px;font-family:arial">
<caption>Common ASCII codes and corresponding characters</caption>
<?php
$str1="32,";
for ($i = 1; $i <= 127; $i++) {
$str1="$str1" . $i . ",";
}
$str1=$str1 . "128";
$a = explode(",", $str1);
for ($j = 32; $j <= 127; $j++) {
if ($j%16==0) {echo "</tr><tr><td>$a[$j] " . chr($a[$j]) . "</td>";}
else { echo "<td>$a[$j] " . chr($a[$j]) . "</td>";}

PHP

126

}
?>
</table>
</body>
</html>

2.

Test the program with a Apache server (XAMPP). It looks like:

3.

Capture a screen shot similar to the above figure and paste it to a Word document named lab8.doc (or
lab8.docx).

Learning Activity #4:


1. In the X:\xampp\htdocs\myphp directory, use Notepad to create a new file named lab8_4.php with the
following contents:
<?php
if ($_POST)
{
$str=$_POST["content"];
$keyword=$_POST["keyword"];
if (strpos($str," $keyword")) {
echo "The keyword \"<b>$keyword</b>\" appears ",
"<b>". substr_count($str," $keyword"). "</b> times in:";
}
else { echo "Not found!"; }
echo "<hr size=1 width=100%>";
$a=split(" ",$str);
for ($i=0;$i<str_word_count($str);$i++) {
if ($a[$i]==$keyword) {
echo "<b style=\"background-color:yellow\">" . $a[$i] . "</b>&nbsp;";
}
else {echo $a[$i] . "&nbsp;";}
}
}
else
{
?>
<p>Enter few a paragraphs of text and a keyword, then click the Search button</p>
<form action="<?php echo $_SERVER['PHP_SELF'];?>" method="post">
<p>Keyword: <input type="text" name="keyword" size="20" /><br>
<textarea rows=10 cols=90 name="content"></textarea><br>
<input type="submit" value="Search" />
</p></form>
<?php
}
?>

PHP

127

2.

Test the program with a Apache server (XAMPP). A sample test result looks like:

to

3.

Capture a screen shot similar to the above figure and paste it to a Word document named lab8.doc (or
lab8.docx).

Learning Activity #5:


1. In the X:\xampp\htdocs\myphp directory, use Notepad to create a new file named lab8_5.php with the
following contents:
<?php
if ($_POST)
{
$msg=$_POST["msg"];
echo "The original message is:<br /><b>" . $msg . "</b>";
echo "<p>The reversed version is:<br />" . strrev("$msg");
}
else
{
?>
<p>Enter a long message (at least 500 characters), then click the Encrypt
button</p>
<form action="<?php echo $_SERVER['PHP_SELF'];?>" method="post">
<textarea rows=5 cols=90 name="msg"></textarea><br>
<input type="submit" value="Encrypt" />
</p></form>
<?php
}
?>

2.

Test the program with a Apache server (XAMPP). A sample output looks like:

to

3.

Capture a screen shot similar to the above figure and paste it to a Word document named lab8.doc (or
lab8.docx).

Submitting the lab


1. Create a .zip file named lab8.zip containing:
Lab8_1.php
PHP

128

2.

Lab8_2.php
Lab8_3.php
Lab8_4.php
Lab8_5.php
Lab8.doc (or .docx and make sure this file contains all the five screen shots)

Upload the zipped file as response to question 11 or Assignment 8 (available in Blackboard).

PHP

129

Appendix: Common String functions


PHP has severs built-in string functions. The following table is a list of common PHP string functions.
Function
chr
chunk_split
crypt
echo
explode
html_entity_decode
htmlentities
htmlspecialchars
implode
ltrim
number_format
ord
parse_str
print
printf
rtrim
setlocale
similar_text
sprintf
sscanf
str_ireplace
str_pad
str_repeat
str_replace
str_shuffle
str_split
str_word_count
strcasecmp
strchr
strcmp
strip_tags
stripos
stristr
strlen
strnatcasecmp
strnatcmp
strncasecmp
strncmp
strpos
strrchr
strrev
strripos
strrpos
strspn
strstr
strtolower
strtoupper
strtr
substr_compare

PHP

Purpose
Returns a specific character, given its ASCII code
Splits a string into smaller chunks
Supports one-way string encryption (hashing)
Displays one or more strings
Splits a string on a substring
Converts all HTML entities to their applicable characters
Converts all applicable characters to HTML entities
Converts special characters to HTML entities
Joins array elements with a string
Strips whitespace from the beginning of a string
Formats a number with grouped thousand separators
Returns the ASCII value of character
Parses the string into variables
Displays a string
Displays a formatted string
Strips whitespace from the end of a string
Sets locale information
Calculates the similarity between two strings
Returns a formatted string
Parses input from a string according to a format
Case-insensitive version of the str_replace function.
Pads a string with another string
Repeats a string
Replaces all occurrences of the search string with the replacement string
Shuffles a string randomly
Converts a string to an array
Returns information about words used in a string
Binary case-insensitive string comparison
Alias of the strstr function
Binary-safe string comparison
Strips HTML and PHP tags from a string
Finds position of first occurrence of a case-insensitive string
Case-insensitive version of the strstr function
Gets a string's length
Case-insensitive string comparisons
String comparisons using a "natural order" algorithm
Binary case-insensitive string comparison of the first n characters
Binary-safe string comparison of the first n characters
Finds position of first occurrence of a string
Finds the last occurrence of a character in a string
Reverses a string
Finds the position of last occurrence of a case-insensitive string
Finds the position of last occurrence of a char in a string
Finds the length of initial segment matching mask
Finds the first occurrence of a string
Converts a string to lowercase
Converts a string to uppercase
Translates certain characters
Binary-safe (optionally case-insensitive) comparison of two strings from an offset

130

substr_count
substr_replace
substr
trim

PHP

Counts the number of substring occurrences


Replaces text within part of a string
Returns part of a string
Strips whitespace from the beginning and end of a string

131

Lecture #9:

PHP and HTML Forms

What is a
PHP form?

The term "PHP forms" is somewhat confusing to new learners. It is actually a combination of PHP
scripts and HTML forms, or in a more technical context, it is the embedding of PHP scripts onto
HTML forms.
Background
The purpose of combining PHP scripts with HTML forms is to integrate the server-side coding
functionality with client-side coding connectivity. PHP is short for "Hypertext Preprocessor". It is a
server-side, cross-platform, HTML embeddable scripting language.
HTML forms are processed by the clients machine, meaning that the clients web browsers will first
connect to the web server, download the HTML code from the server back to the client machine, and
the execute the code using the local web browser. The clients browser will maintain a dedicated
connection (officially known as session) to upload the users entries through the session to the
server. The server in turn processes the user entries using PHP code and the PHP engine.
HTML forms provide an interface framework of for users to work with. It acts as an intermediary
between the user and the remote server. PHP code, however, allows applications to retrieve input,
process input, and return output.

Creating
HTML
forms

An HTML form is a like a Q&A (question and answer) web document with specialized elements
called controls (e.g.: textboxes, checkboxes, radio buttons, drop-down menus, and textareasand
labels on those controls. Users generally complete an HTML form by modifying its controls (e.g.:
entering text or selecting menu itemsbefore submitting the form to an agent for processing (e.g., to a
Web server or to a mail server)
The <form>...</form> tags marks the beginning and ending of an HTML form. All the components
of HTML forms are to be included by them. The <form> element has several attributes that will
work with PHP codes.
name = "Name". This attribute names the form so that it may be identified by PHP script.
action = "URL". This attribute specifies the URL of form processing agent, namely the address
of PHP code that will process the form).
method = "get|post". This attribute specifies which HTTP method will be used to submit the
form data set. Possible (case-insensitive) values are "get" (the default) and "post".
enctype = "content-type". This attribute specifies the content type used to submit the form to the
server (when the value of method is "post"). The default value for this attribute is
"application/x-www-form-urlencoded".
For example:
<form name=" " action=" " method=" " enctype=" ">< /form>
Form submission method
The method attribute of the FORM element specifies the HTTP method used to send the form to the
processing agent. This attribute may take two values: get and post. The major differences are:
get: Using the "get" method, the form data set is appended to the URL specified by the action
attribute (with a question-mark ("?") as separator) and this new URL is sent to the processing
agent. Some people believe this method is less secured. The following example demonstrate
how to use the get method.
<form name="form1" action="test.php" method="get"
enctype="text/plain">< /form>

PHP

132

post: Using the "post" method, the form data set is included in the body of the form and sent to
the processing agent. The following demonstrates how to use the post method.
<form name="form1" action="test.php" method="post"
enctype="text/plain">< /form>

W3C has the following suggestion:


The "get" method should be used when the form is idempotent (i.e.,
causes no side-effects). Many database searches have no visible
side-effects and make ideal applications for the "get" method.

If the service associated with the processing of a form causes side effects. For example, if the form
modifies a database or subscription to a service, the "post" method should be used.
Form Action
The ACTION attribute sets the URL to which the form content is sent for processing. The following
example uses the ACTION attribute to specify a URL for the mailto protocol using the "Get"
method. Using PHP to process email, however, is the topic for later lecture.
<form ACTION="mailto:sales@cnn.com" method="get">

Now, in order to create a form named "request" which will point the action of the HTML form to a
myform.php script, the HTML code will look like:
<form name="request" method="post" action="myform.php">

This "request" form does not have a control in it, so the user will not see anything. You need to add
form fields with controls, which allow you to specify how you want the users to enter data with
correct data types.
Use $_SERVER['PHP_SELF'] as a form action.
Remember the $_SERVER['PHP_SELF']? It is a predefined variable that returns the filename of the
currently executing script. The following example, use $_SERVER['PHP_SELF'] to tell the PHP
script to send the form content to the script itself for processing.
<form action="<?php echo $_SERVER['PHP_SELF']; ?>"
method="post">
The $_SERVER auto-global array holds various useful server- and request-specific info. The
PHP_SELF element of $_SERVER holds the filename of the currently executing script (relative to
your web site's document root directory).
For example, consider this form:
<form action="<?php echo $_SERVER['PHP_SELF']; ?>"
method="POST">
Pick some desserts: <select name="sweet[]" multiple>
<option value="puff"> Sesame Seed Puff</option>
<option value="square"> Coconut Milk Gelatin Square</option>
<option value="cake"> Brown Sugar Cake</option>
<option value="ricemeat"> Sweet Rice and Meat</option>
</select>
<input type="submit" name="Order">
</form>

If you pick Sesame Seed Puff and Brown Sugar Cake and submit the form, then
$_POST['sweet'] is itself an array. $_POST['sweet'][0] is puff and $_POST['sweet'][2] is cake. That's
PHP

133

because the name attribute of the <select> element is sweet[]. If the name was just sweet, then
$_POST['sweet'] would be a string, holding only one of the selected values.
The Input element
The Input element with the type attribute specifies the type of control to create. Options are:
text. <input type="text"> creates a single-line text input control.
password. <input type="password"> creates a single-text text input control, but the text is
rendered in such a way as to hide the characters.
checkbox. <input type="checkbox"> creates a checkbox.
radio. <input type="radio"> creates a radio button.
submit. <input type="submit"> creates a submit button.
reset. <input type="reset"> creates a reset button.
file. <input type="file"> creates a file select control. User agents may use the value of the
value attribute as the initial file name.
hidden. <input type="hidden"> creates a hidden control.
image. <input type="image" src="myicon.gif"> creates a graphical submit button. You
need to use the src attribute specifies the URL of the image that will decorate the button.
button. <input type="button" value="Display Answer"> creates a generic push
button. You need to use the value attribute to specify the button's label.
In addition to the <input> element, the <TEXTAREA> element defines a form control for the user to
enter multi-line text input. The required ROWS and COLS attributes specify the number of visible
rows and columns, respectively, in a visual browser.
The <SELECT> element defines a form control for the selection of options. The following example
uses the SELECT element to create a drop-down list box. It uses the select element to create a multiselect list box by setting the SIZE and MULTIPLE attributes. To retrieve the selected options from a
multi-select list box, iterate through the options collection and check to see where SELECTED is:
<form>
<select name="fruit" size="1">
<option value="1">apple
<option value="2">orange
<option value="3" selected>banana
</select>
</form>

The following code explains how all the controls are created with the input element. Notice that all
the controls have an identification assigned by the name attribute.
<html><body>
<!-- demo9_1.php -->
<form name="demo" action="demo.php" method="post"
enctype="multipart/form-data">
UserID: <input type="text" name="uid" size="20"><br>
Password: <input type="password" name="psd" size="20"><br>
<p><input type="hidden" value="You can see this hidden textbox!">
<input type="file" name="uploadfile">
<p>What is your blood type?
<input type="radio" name="Btype"
<input type="radio" name="Btype"
<input type="radio" name="Btype"
<input type="radio" name="Btype"

value="A">A.
value="B">B.
value="O">O.
value="AB">AB.

<p>What is/are class(es) you will take next term? (Check all that

PHP

134

apply.)<br>
<input type="checkbox"
<input type="checkbox"
<input type="checkbox"
<input type="checkbox"

name="subject"
name="subject"
name="subject"
name="subject"

value="CIS109">CIS109
value="CIS179">CIS179
value="CIS218">CIS218
value="CIS246">CIS246

<p>Payment method: <select name="payment">


<option value="COD">COD
<option value="Check">Check
<option value="Credit Card" selected>Credit Card
</select>
<p>Comment:<textarea name="comment" rows=5 cols=90></textarea>
<p><input type="reset">
<input type="submit">
<input type="button" value="Generic Button">
<input type="image" src="go.gif">
</form>
</body></html>

The value of the hidden attribute will not be displayed, but it will be included in the body of the form
and sent to the demo.php script. Notice that the enctype attribute is given the value "multipart/formdata". According W3C, the value "multipart/form-data" should be used in combination with the
INPUT element, type="file"; otherwise, you will expect to see an error message.
Displaying
HTML
Forms in
PHP

You can either use the echo construct display the form in a PHP code section or use plain HTML
outside the PHP code section. Compare the following two examples, they generate exactly the same
result:
<?php
echo "<form action='1.php'
method='post'>\n
<input type='text' name='name'>\n
<input type='submit'
value='Go'>\n
</form>\n";
?>

<?php
...some PHP code...
?>
<form action="1.php"
method="post">
<input type="text" name="name">
<input type="submit" value="Go">
</form>
<?php
?>

Verify if a particular field is blank


The second step is to check if the user completes the form or make sure the user entered all the
required data. The following example illustrates three different ways to validate required data.
$_POST["first"]=="".
empty($_POST["last"]).
!$_POST["address"].
Choose whichever you feel comfortable to work with or whenever it is deemed appropriate.
<?php
if ($_POST)
{
$err= "Error:<br>";
if ($_POST["first"]=="") { $err .= "<li>First name is required!"; }
if (empty($_POST["last"])) { $err .= "<li>Last name is
required!"; }

PHP

135

if (empty($_POST["telephone"])) { $err .=
required!"; }
echo $err;
}
else
{
?>

"<li>Telephone is

<form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post">


First Name: <input type="text" name="first"><br>
Last Name: <input type="text" name="last"><br>
Telephone: <input type="text" name="telephone"><br>
<p><input type="submit" value="submit">
</form>
<?php
}
?>

If you simply click the button without entering anything, the output looks like:
Error:

First name is required!

Last name is required!

Telephone is required!

Getting the
Form
Information

When the user submits the form with entries, the server-side script must be able to get the
information. Since, there are two submission methods, GET and POST, there are three different
methods, $_POST[ ], $_GET[ ], and $_REQUEST[ ] of getting the data into PHP depending on the
method used on the <form> element. In PHP, they are known as predefined variables.
$_POST[ ]
To get a variable which has been sent to a script using the POST method you use the following
syntax:
$VariableName=$_POST['VariableName'];

which basically takes the variable (the name of a form field) from the POST and assigns it to the
variable $VariableName.
$_GET[ ]
To use the GET method you should use the following syntax:
$VariableName=$_GET['VariableName'];

$_REQUEST[ ]
The $_REQUEST works with the method="post" and method="get" input mechanisms. It even
works with COOKIE and SESSION. The syntax is:
$VariableName=$_REQUEST['VariableName'];

The benefit of using $_REQUEST[ ] is that you dont need to worry where the user entries are
coming from. $_REQUEST will automatically determine whether or not it came from $_POST,
$_GET, $_COOKIE, $_SESSION, etc. Notice that using $_REQUEST or. $_POST makes no
difference in the results.
Processing
PHP

The term "processing forms" refers to using PHP script to get the user entries, validate the users, and

136

Forms

return the outputs. To make your script more robust, it is useful to have some sort of checking to
ensure that all essential fields have been completed before sending the message to the web server.
Validating if a value matches with the criteria prior to the client sending incorrect input to your
application can save a lot of server-side validation.
Verify if the form has been filled out
The first step of validation is to check whether or not a form has been filled, the easiest way is to use
one of the following options depending on the value of method attribute:
if ($_POST) { what to do if form is filled } else { display the form
with method="post"}

and
if ($_GET) { what to do if form is filled } else { display the form
with method="get"}

Compare the following two examples.


<?php
if ($_POST)
{
echo $_REQUEST["fn"];
}
else
{
?>

<?php
if ($_GET)
{
echo $_REQUEST["fn"];
}
else
{
?>

<form action="" method="post">


<input type="text" name="fn"
size="20">
<input type="submit"
value="submit">
</form>

<form action="" method="get">


<input type="text" name="fn"
size="20">
<input type="submit"
value="submit">
</form>

<?php
}
?>

<?php
}
?>

Another way to verify form input is to use either isset() or empty(). They are both PHP built-in
functions.
isset(). The function isset($var) will return true, if the variable $var has been set to a value. It
will return false, if $var has not been set to a value.
empty(). The function empty($var) assumes that the variable $var has been set to a value. It
tests what the value of $var has been to. If $var has been set to the null-string (""), then
empty($var) will return true. If $var has been set to any other string it will return false.
In the following two examples, the isset() function checks whether or not $_REQUEST["fn"] is
given a value.
If yes, it proceeds to display the value. If not, it proceeds to display the form. Similarly, the empty()
function check whether or not $_REQUESTION["fn"] equals null value ("") and then proceeds.
<?php
if (isset($_REQUEST["fn"]))
{
echo $_REQUEST["fn"];
}
else
{
?>

PHP

<?php
if (empty($_REQUEST["fn"])=="")
{
echo $_REQUEST["fn"];
}
else
{
?>

137

<form action="" method="post">


<input type="text" name="fn"
size="20">
<input type="submit"
value="submit">
</form>

<form action="" method="post">


<input type="text" name="fn"
size="20">
<input type="submit"
value="submit">
</form>

<?php
}
?>

<?php
}
?>

Validating and Processing textbox


The purpose of textbox is to allow the user to input text data. Text data are either strings or numbers.
Only one line of text is allowed in each textbox. Therefore, textbox validation is simply to determine
whether the entry is correct, matched pattern, or wanted. Pattern matching requires knowledge of
PHP expression rules, and is to be discussed in later section.
In the following example, $_POST["uid"] represents the value entered to the textbox named "uid",
while $_POST["psd"] represents the "psd" textbox. Both textboxes are to be checked to determine if
they equal the pre-defined values. Notice && is the AND operator.
<?php
//demo7_2.php
if ($_POST)
{
if (($_POST["uid"]=="cis246") && ($_POST["psd"]=="apple")) {
header("Location: http://www.cnn.com"); exit; }
else {echo $_POST["err"]; exit; }
}
else
{
?>
<form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post">
UserID: <input type="text" name="uid" size="15"><br>
Password: <input type="text" name="psd" size="15">
<input type="hidden" name="err" value="You are not authorized!">
<input type="image" src="go.gif" width="30" height="17">
</form>
<?php
}
?>

Notice that $_POST["err"] is the value of the hidden textbox.


Validating and Processing Radio Buttons
Radio buttons allow for the direct input of a restricted amount of input.
check the value. When a radio button contains value, as assigned to the value attribute of <input
element>, you can simply verify the user entry.
matches.
use the "checked" keyword. Radio buttons are to be checked by the user, you can use the
"checked" keyword to verify if a radio button is checked by the user.
Options in a radio button group share the same control name, so they are mutually exclusive. When
one is switched "on", all others with the same name are switched "off".
PHP

138

In the following example, question 1 and 2 each use one of the validation method. In question 1,
each radio button is given the same name "r1". In question 2, the name is an array $r2[ ] with four
keys 0, 1, 2, and 3. It is based on:
$r2[]="A";
$r2[]="B";
$r2[]="C";
$r2[]="D";

The $_POST["r1"] represents the value of the user-checked radio button in question 1, and is tested
with the == operator. The $_POST["r2[0]"].checked use the checked keyword to verify if the r2[0]
element of the r2[ ] array is checked. See the following example.
<?php
//demo7_3.php
if ($_POST)
{
echo "<ol>";
if ($_POST["r1"]=="B") { echo "<li>Correct!<br>"; }
else {echo "<li>Wrong!<br>";}
if ($_POST["r2[0]"].checked) { echo "<li>Correct!<br>"; }
else {echo "<li>Wrong!<br>";}
echo "</ol>";
}
else
{
?>
<form action="<?php echo $_SERVER['PHP_SELF'];
<p>1. __ is the capital city of California.
<br><input type="radio" name="r1" value="A">A.
<br><input type="radio" name="r1" value="B">B.
<br><input type="radio" name="r1" value="C">C.
<br><input type="radio" name="r1" value="D">D.

?>" method="post">
San Diego
Sacremento
San Francisco
Santa Barbara

<p>2. Which city has the largest population?


<br><input type="radio" value="A" name="r2[]">A.
<br><input type="radio" value="B" name="r2[]">B.
<br><input type="radio" value="C" name="r2[]">C.
<br><input type="radio" value="D" name="r2[]">D.

Seattle
Houston
New York
Boston

<p><input type="submit" value="Check Answer">


</form>
<?php
}
?>

Validating and Processing Checkbox


The major difference as to when to checkbox and when to use radio button is that one or more
checkboxes in a group must be checked, while only one radio button in a group can be checked.
However, their validations are similar.
Checkboxes are on/off switches that may be toggled by the user. A switch is on when the control
elements checked attribute is set. In question 2 below, the name c1 is an array with four keys 0, 1, 2,
and 3. It is based on:
PHP

139

$c1[0]="";
$c1[1]="";
$c1[2]="";
$c1[3]="";

All elements in the $c1 array are set to have null values. When selecting an option, the user toggles
the switch, and sets the value to "on". The validation is based on checking whether or not an option
is turned on.
<?php
if ($_POST)
{
if (($_POST["London"]=="on" && $_POST["Paris"]=="on"))
{ echo "1. Correct!"; }
else { echo "1. Wrong!"; }
if ($_POST['c1']=="Taipei") {echo "2. correct!"; }
else { echo "2. Wrong!"; }
}
else
{
?>
<form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post">
<p>1. Which two cities did I visited in year 2001?
<br><input type="checkbox" name="London">London
<br><input type="checkbox" name="Paris">Paris
<br><input type="checkbox" name="Milan">Milan
<br><input type="checkbox" name="Vienna">Vienna
<p>2. __ is a city in Asia.
<br><input type="radio" name="c1"
<br><input type="radio" name="c1"
<br><input type="radio" name="c1"
<br><input type="radio" name="c1"

value="London">A. London
value="Taipei">B. Taipei
value="Milan">C. Milan
value="Tokyo">D. Chicago

<p><input type="submit" value="submit">


</form>
<?php
}
?>

Validating and Processing Drop-Down Menu


Validating a drop-down menu is fairly simple in PHP. It is just the matter of verifying what option
the user chooses. However, when you allow the user to select more than one option, you can
consider using the array, as shown in the following example.
<?php
if ($_POST)
{
echo "You select: ";
foreach($_POST["fruit"] as $fruit) {
echo $fruit, " ";
}
}
else
{
?>

PHP

140

<form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post">


<select name="fruit[]" multiple="true">
<option>apple</option>
<option>orange</option>
<option>banana</option>
<option>tangerine</option>
</select>
<p><input type="submit" value="Send"></form>
<?php
}
?>

Using PHP
newt_ Form
functions
Linux
servers only

This is a PHP language extension for RedHat Linux Newt library, a terminal-based window and
widget library for writing applications with user friendly interface. Once this extension is enabled in
PHP it will provide the use of Newt widgets, such as windows, buttons, checkboxes, radiobuttons,
labels, editboxes, scrolls, textareas, scales, and more.
Note: This module uses the functions of the RedHat Newt library. You will need at least libnewt
version >= 0.51.0.
The newt_form() function
This function creates a new HTML form.
For example, the following code displays a single button "Quit", which closes the application once
it's pressed.
<?php
newt_init();
newt_cls();
$myform = newt_form();
$button = newt_button (5, 12, "Quit");
newt_form_add_component ($myform, $button);
newt_refresh ();
newt_run_form ($myform);
newt_finished ();
newt_form_destroy ($myform);
?>

You can visit http://www.php.net/manual/en/function.newt-form.php for more detail.


Using PHP
Regular
Expression
to Validate
Forms

In a Unix based language like PHP, regular expression make data validation more meaningful, but it
is also confusing to new learners. Regular expression uses many symbols, known as wildcard
characters. For example, apple means a string that has the text apple in it. *le, however, could
be the string 'able", "nicole", "impossible", etc.
In PHP, you can use either the ereg() or eregi() built-in function can search a string for matches of a
regular expression. The ereg() function is ideal for validating user entries. Notice that in PHP 5.3.0
deprecated ereg() and eregi() methods. You need to use their replacements now.
ereg(): use preg_match() with the i modifier
eregi(): use preg_match() with the i modifier
In the following example, the ereg() function verifies if the $str string contains an @ character, and
return 1 or true if the string does. By combining PHP regular expression, pattern matching, and the
ereg() function, you can validate user's form input for proper formatting.

PHP

141

<?php
$str="jsmith@cis246.com";
echo ereg("@", $str), "<br>"; // return 1 or true
?>

With PHP 5.3.0, the above code will generate the following error message.
Deprecated: Function ereg() is deprecated in G:\xampp\htdocs\.....
on line 3

For PHP 5.3.0 and later version, the code should be:
<?php
$str="jsmith@cis246.com";
echo preg_match("/@/i", $str), "<br>"; // return 1 or true
?>

The eregi() function is identical to ereg() except that it ignores case distinction (or is case
independent) when matching alphabetic characters. For example:
<?php
if (eregi("H", "php")) {
echo "it contains a 'h' or 'H'!";
}
?>

In PHP 5.3.0 or later, the code should be:


<?php
if (preg_match("/H/i", "php")) {
echo "it contains a 'h' or 'H'!";
}
?>

PHP Regular Expression


To learn the basic syntax of PHP regular expressions, let's start with two special symbols, "^" and
"$". "^" indicates the beginning of a string, while "$" indicates the end. A brief and a detailed
reference are available at the http://www.cs.wcupa.edu/~rkline/php/regex-progs.html. For example:
"^Java": matches any string that starts with "Java". E.g. Java, JavaScript, JavaBeans, JavaPlus.
"ood$": matches a string that ends in the substring "ood". E.g. food, good, or hood.
"^714$": a string that starts and ends with "714". The only candidate is "714" itself.
In the following example, regular expression uses some wildcard characters.
<?php
$str="CIS246 PHP Programming";
//search from the beginning of a string, use ^
echo preg_match("/^CIS/i", $str), "<br>"; // return 1 or true
//search at the end of a string, use $
echo preg_match("/ing$/i", $str), "<br>"; // return 1 or true
// search for any character, use the dot
echo preg_match("/PHP/i", $str), "<br>"; // return 1 or true
?>

Old format is:


<?php

PHP

142

$str="CIS246 PHP Programming";


//search from the beginning of a string, use ^
echo ereg("^CIS", $str), "<br>"; // return 1 or true
//search at the end of a string, use $
echo ereg("ing$", $str), "<br>"; // return 1 or true
// search for any character, use the dot
echo ereg("PHP", $str), "<br>"; // return 1 or true
?>

Below is a list of some meta-characters and character classes for a quick glance - each will be
explained in further detail with examples. Keep in mind that a "match" can be as simple as a single
character or as complex as a sequence of literals and meta-characters in nested and compounded
combinations.
Meta-character
\
. (period)
x
^x
[x]
| (pipe)
()
{}
{x}
{x,}
{x,y}
?
*
+
^
$

Match
the escape character - used to find an instance of a meta-character like a
period, brackets, etc.
match any character except newline
match any instance of x
match any character except x
match any instance of x in the bracketed range - [abxyz] will match any
instance of a, b, x, y, or z
an OR operator - [x|y] will match an instance of x or y
used to group sequences of characters or matches
used to define numeric quantifiers
match must occur exactly x times
match must occur at least x times
match must occur at least x times, but no more than y times
preceding match is optional or one only, same as {0,1}
find 0 or more of preceding match, same as {0,}
find 1 or more of preceding match, same as {1,}
match the beginning of the line
match the end of a line

Be familiar with three symbols, '*', '+', and '?'. They are used to denote the number of times a
character or a sequence of characters may occur in a string. What they mean is: "zero or more", "one
or more", and "zero or one." For example:
"cp*": matches a string that starts with a "c", and followed by zero or more p's. E.g. "c", "cp",
"cp", "cppp", etc.
"cp+": matches a string that starts with a "c", and followed by at least one b. E.g. "cp", "cpp",
etc.
"cp?":
"c?p+$": one possible "c" followed by one or more p's as ending of a string.
A sample code will be,
<?php
$str="714-868-5293";
//use * to specify that a character may (or may not) exist
//, and is repeatable
echo preg_match("/-*/i", $str), "<br>"; // return 1 or true
echo preg_match("/!*/i", $str), "<br>"; // return 1 or true

PHP

143

// use + for a character that must exist and is repeatable


echo preg_match("/g+/i", "dog"), "<br>"; // return 1 or true
echo preg_match("/g+/i", "doggy"), "<br>"; // return 1 or true
// use ? to specify a character must either exist just once
//, or not at all
echo preg_match("/c?/i", "cypress"), "<br>"; // return 1 or true
echo preg_match("/c?/i", "press"), "<br>"; // return 1 or true
?>

The old format is:


<?php
$str="714-868-5293";
//use * to specify that a character may (or may not) exist
//, and is repeatable
echo ereg("-*", $str), "<br>"; // return 1 or true
echo ereg("!*", $str), "<br>"; // return 1 or true
// use + for a character that must exist and is repeatable
echo ereg("g+", "dog"), "<br>"; // return 1 or true
echo ereg("g+", "doggy"), "<br>"; // return 1 or true
// use ? to specify a character must either exist just once
//, or not at all
echo ereg("c?", "cypress"), "<br>"; // return 1 or true
echo ereg("c?", "press"), "<br>"; // return 1 or true
?>

Use braces to indicate a range in the number of occurrences. For example,


"fo{2}": matches a string that starts with an "f" and is followed by exactly two o's, that is "foo".
"fo{2,}": matches a string that starts with an "f" and isfollowed by at least two o's. E.g. "foo",
"fooo", "fooooo", etc.
"fo{3,5}": matches a string that starts with an "f" and is followed by three to five o's. E.g.
"fooo", "foooo", and "fooooo".
Heres a coding sample:
<?php
//match certain amount of characters in a string
// 2 l's at the beginning
echo preg_match("/^Il{2,}/i", "Illinois"), "<br>";
// 2 0's at the end
echo preg_match("/o{2,}$/i", "Waterloo"), "<br>";
?>

The old format is:


<?php
//match certain amount of characters in a string
// 2 l's at the beginning
echo ereg("^Il{2,}", "Illinois"), "<br>";
// 2 0's at the end
echo ereg("o{2,}$", "Waterloo"), "<br>";
?>

Note that you must always specify the first number of a range (i.e, "{0,2}", not "{,2}"). Also, as you
might have noticed, the symbols '*', '+', and '?' have the same effect as using the bounds "{0,}",
PHP

144

"{1,}", and "{0,1}", respectively. Use parentheses to quantify a sequence of characters. For example:
"m(ba)*": matches a string that starts with a "m" and is followed by zero or more copies of the
sequence "ba". E.g. "mba", "mbaba", "mbababa".
"m(ba){1,5}": one through five copies of "ba."
For example:
<?php
//search for a match that has
echo preg_match("/w{1,3}$/i",
echo preg_match("/w{1,3}$/i",
echo preg_match("/w{1,3}$/i",
?>

1 to 3 'w' characters at the end


"w"), "<br>"; // return 1 or true
"ww"), "<br>"; // return 1 or true
"www"), "<br>"; // return 1 or true

The old format is:


<?php
//search for a match
echo ereg("w{1,3}$",
echo ereg("w{1,3}$",
echo ereg("w{1,3}$",
?>

that has 1 to 3 'w' characters at the end


"w"), "<br>"; // return 1 or true
"ww"), "<br>"; // return 1 or true
"www"), "<br>"; // return 1 or true

There's also the '|' symbol, which works as an OR operator. For example,
"oo|ee": matches a string that has either "oo" or "ee" in it. E.g. food, teeth, feet, cook.
"(oo|ee)t": a string that has either "eet" or "oot". E.g. foot, feet.
"(oo|ee)*th": a string that has a sequence of alternating oo's and ee's ending with "th". For
example, tooth, teeth.
A sample code will look like:
<?php
echo preg_match("/^(C|c).+$/i", "Cypress"), "<br>";
echo preg_match("/^(C|c).+$/i", "cypress"), "<br>";
?>

The old format is:


<?php
echo ereg("^(C|c).+$", "Cypress"), "<br>";
echo ereg("^(C|c).+$", "cypress"), "<br>";
?>

Bracket expressions specify which characters are allowed in a single position of a string:
"[xy]": matches a string that has either a "x" or a "y" (same as "x|y").
"[w-z]": a string that has lowercase letters 'w' through 'z'.
"^[a-zA-Z]": a string that starts with a letter, regardless upper or lower case.
"[0-9]%": a string that has a single numeral before a percent sign.
",[a-zA-Z0-9]$": a string that ends in a comma followed by an alphanumeric character.
You can also exclude characters by simply using a '^' as the first symbol in a bracket expression. For
example, "%[^a-zA-Z]%" matches a string with a character that is not a letter between two percent
signs. A dot ( . ) stands for any single character. For example:
"D.[0-9]": matches a string that starts with an "D", and followed by one character and then a
digit. E.g. Ds1, DS5, DD8.
"^.{3}$": a string with exactly 3 characters. E.g.: car, elf, egg, or may.
For example:
PHP

145

<?php
// search for a match of one character followed
// by 2 p's in a string
echo preg_match("/.p{2}/i", "apple"), "<br>"; // return 1 or true
// search for a match of two characters followed
// by 2 p's in a string
echo preg_match("/..p{2}/i", "maple"), "<br>"; // return 1 or true
?>

The old format is:


<?php
// search for a match of one character followed
// by 2 p's in a string
echo ereg(".p{2}", "apple"), "<br>"; // return 1 or true
// search for a match of two characters followed
// by 2 p's in a string
echo ereg("..p{2}", "maple"), "<br>"; // return 1 or true
?>

In order to be taken literally, you must escape some characters with a backslash ('\'). There are only a
handful of symbols that you have to escape: ^, $, (, ), ., [, |, *, ?, +, \ and {. As explained earlier, they
are wildcard characters and they have special meaning.
Verifying the space character
To match the space character in a search string, we use the predefined Posix class, [[:space:]]. The
square brackets indicate a related set of sequential characters, and ":space:" is the actual class to
match (which, in this case, is any white space character). White space includes the tab character, the
new line character, and the space character.
<?php
echo preg_match("/[[:space:]]/i", "Jennifer Lopez");
?>
<br>Grouping patterns
<br>To search for a numerical string of characters:
<?php
echo preg_match("/^[0-9]+$/i", "012345789");
?>

The old format:


<?php
echo ereg("[[:space:]]", "Jennifer Lopez");
?>
<br>Grouping patterns
<br>To search for a numerical string of characters:
<?php
echo ereg("^[0-9]+$", "012345789");
?>

To specify that a case-sensitive sequence of characters, use:


[a-z] for lower case, and
[A-Z] for upper case.
On the contrary, if either lower case or upper case characters are acceptable, use:
[a-zA-Z]

PHP

146

When there is a need to add a space between two substrings, such as the space in "Jennifer Lopez",
use:
[[:space:]]{1}

For example:
<?php
echo preg_match("/^[a-z]+$/i", "php"), "<br>";
echo preg_match("/^[A-Z]+$/i", "PHP"), "<br>";
echo preg_match("/^[a-zA-Z]+$/i", "pHp"), "<br>";
echo preg_match("/^[a-zA-Z]+[[:space:]]{1}[a-zA-Z]+$/i", "PHP
Programming"), "<br>";
?>

The old format is:


<?php
echo ereg("^[a-z]+$", "php"), "<br>";
echo ereg("^[A-Z]+$", "PHP"), "<br>";
echo ereg("^[a-zA-Z]+$", "pHp"), "<br>";
echo ereg("^[a-zA-Z]+[[:space:]]{1}[a-zA-Z]+$", "PHP Programming"),
"<br>";
?>

In the following example, heres is a very common validation for the email format.
<?php
$email = "jlo@cis246.com";
preg_match('/^[a-zA-Z0-9._-]+@[a-zA-Z0-9-]+\.[a-zA-Z.]{2,4}$/i',
$email)
?>

^[a-zA-Z0-9._-] validates the 'username' section of the email address.


+ indicates "one or more characters".
@ only one occurrence of @.
[a-zA-Z0-9._-]+\. validates the domain name in the email address.
+ require one or more of those characters.
\. use the backslash followed a dot sign to escape the sequence. This tells the expression that a
dot is required at this point in the expression.
[a-zA-Z] allows only alphabets either in lower or upper cases.
{2,4}$ require between 2 and 4 of the characters from the square brackets to be included in the
email address. So com, net, org, uk, au, etc. are all valid, but anything longer than these will not
be accepted.

To verify hyperlinks include SSL-enabled URLs, use:


^https{0,}\\:\\/\\/[a-z0-9\-]+\.([a-z0-9\-]+\.)?[a-z]+

For example:
<?php
if (!$_POST)
{
?>
<form action="<?=$_SERVER['PHP_SELF']; ?>" method="post">
Enter a complete URL, for example,
<pre>http://www.cypresscollege.edu or
https://www.att.com or
</pre>

PHP

147

<input type='text' name='email' size="20">


<p><input type='submit' value='Check'>
</form>
<?php
}
else
{
if (preg_match("/^[a-zA-Z0-9._-]+@[a-zA-Z0-9._-]+\.([a-zAZ]{2,4})$/i",$_POST["email"]))
{
echo "Valid web address!";
} else {
echo "Invalid web address!";
}
}
?>

Validating E-mail Addresses, use:


^[_a-z0-9-]+(\.[_a-z0-9-]+)*@[a-z0-9-]+(\.[a-z0-9-]+)*$

To validate telephone number in (999)999-9999 format, use:


^\([[:digit:]]{3}\)[[:digit:]]{3}-[[:digit:]]{4}$

Validation and recombination


ereg() also has some advanced functionality. If matches are found for parenthesized substrings of
pattern and the function is called with the third argument $rags, the matches will be stored in the
elements of the array rags. $rags[1] will contain the substring which starts at the first left
parenthesis; $rags[2] will contain the substring starting at the second, and so on. $rags[0] will
contain a copy of the complete string matched.
The following code snippet takes a date in ISO format (YYYY-MM-DD) and prints it in
DD.MM.YYYY format.
<?php
$date = "2006-12-31";
preg_match("/([0-9]{4})-([0-9]{1,2})-([0-9]{1,2})/i", $date, $rags);
echo "$rags[3].$rags[2].$rags[1]";
?>

The old format is:


<?php
$date = "2006-12-31";
ereg ("([0-9]{4})-([0-9]{1,2})-([0-9]{1,2})", $date, $rags);
echo "$rags[3].$rags[2].$rags[1]";
?>

The output is:


31.12.2006

To learn more about PHP regular expression, visit the OReillys Regular Expression Pocket
Reference site (http://oreilly.com/catalog/regexppr/chapter/) and download a copy of the sample
chapter in PDF format.
Review
Questions
PHP

1. Which is the correct way to use the <form> tag in PHP?


A. <form action=post method=get src=test.php>

148

B. <form action=test.php method=get>


C. <form action=test.php method=post>
D. <form action=post method=get href=test.php>
2. Which cannot verify if a form has been filed out?
A. if ($_POST) { } else { }
B. if ($_POST==) { } else { }
C. if !($_POST) { } else { }
D. if !($_POST) is nothing { } else { }
3. Which statement is correct?
A. The post method is less secured than the get method.
B. The post method will display the variable name and its value in a key=value format.
C. The get method will not display the variable name and its value in a key=value format.
D. The benefit of using $_REQUEST[ ] is that you dont need to worry where the user entries are
coming from.
4. Which cannot verify if a particular field is blank?
A. $_POST["first"]=="".
B. $_POST["first"]!=""
C. empty($_POST["first"]).
D. !$_POST["first"].
5. Which will tell the PHP to send the form contents o the script itself for processing?
A. <form action=$_SERVER['PHP_SELF']; method=post>
B. <form action=echo $_SERVER['PHP_SELF']; method=get>
C. <form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post">
D. <form action="<? $_SERVER['PHP_SELF']; ?>" method="post">
6. Which statement is correct?
A. The isset($var) function will return true if the variable $var has been set to a value.
B. The isset($var) function will return false if the variable $var has been set to a value.
C. The isset($var) function will return the null string () if the variable $var has been set to a value.
D. None of the above
7. When validating PHP radio buttons, you can use the __ keyword to verify if a radio button is
checked by the user.
A. checked
B. on
C. selected
D. 1
8. Given the following PHP code, the output is __.
<?php echo ereg("@", "cis246@cpc.com"); ?>

A. true
B. false
C. 1
D. 0
9. Which mata-character matches any character except newline?
A. . B. ^ C. ? D. *
10. In PHP regular expression, [0-9] means __.
A. between 0 and 9
PHP

149

B. no occurrences of numbers 0-9 inclusive


C. numbers 0-9 inclusive
D. numbers 0-9 exclusive

PHP

150

Lab #9

PHP and HTML Forms

Learning Activity #1: Basic Form Validation


1. In the X:\xampp\htdocs\myphp directory (create the myphp subdirectory if it does not exist), use Notepad
to create a new file named lab9_1.php with the following contents:
<?php
if ($_POST) {
$grade=$_POST["quiz"];
if ($grade >= 90) { echo "A"; }
elseif ($grade >= 80) { echo "B"; }
elseif ($grade >= 70) { echo "C"; }
elseif ($grade >= 60) { echo "D"; }
else { echo "F"; }
}
else
{
?>
<form method="post" action="<?php echo $_SERVER['PHP_SELF'];?>">
Grade: <input type="text" name="quiz" size=3> (i.e. 87)
<input type="submit" value="submit">
</form>
<?php } ?>

2.

Test the program with a Apache server (XAMPP).

3.

Capture a screen shot similar to the above figure and paste it to a Word document named lab9.doc (or
lab9.docx).

Learning Activity #2: Validation Email Address and telephone number


4. In the X:\xampp\htdocs\myphp directory, use Notepad to create a new file named lab9_2.php with the
following contents. Notice the way I validate if the field is filled:
<?php
if (!$_POST)
{
?>
<form action="<?=$_SERVER['PHP_SELF']; ?>" method="post">
<p>Email Address: <input type="text" name="email" size="40">
<p>Telephone: <input type="text" name="phone" size="20"> (i.e. 714-123-4567)
<p><input type="submit" value="Submit">
</form>
<?php
}
else
{

PHP

151

if (preg_match("/^[a-zA-Z0-9._-]+@[a-zA-Z0-9._-]+\.([a-zAZ]{2,4})$/i",$_POST["email"]))
{ echo "Valid email address!<br>"; }
else { echo "Invalid email address!<br>"; }
if (preg_match("/^[[:digit:]]{3}-[[:digit:]]{3}[[:digit:]]{4}$/i",$_POST["phone"]))
{ echo "Valid phone number!<br>"; }
else { echo "Invalid phone number!<br>"; }
}
?>

5.

Test the program.

to
6.

Capture a screen shot similar to the above figure and paste it to a Word document named lab9.doc (or
lab9.docx).

Learning Activity #3:


1. In the X:\xampp\htdocs\myphp directory, use Notepad to create a new file named lab9_3.php with the
following contents:
<?php
if ($_POST)
{
$address = $_POST['urls'];
header("Location: $address ");
exit;
}
else
{
?>
<form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post">
<select name="urls">
<option value="http://www.cnn.com">CNN</option>
<option value="http://www.abc.com">ABC</option>
<option value="http://www.hbo.com">HBO</option>
<option value="http://www.pbs.com">PBS</option>
<option value="http://www.fox.com">FOX</option>
</select>
<p><input type="submit" value="Send"></form>
<?php
}
?>

2.

Test the program with a Apache server (XAMPP).

PHP

152

to
3.

Capture a screen shot similar to the above figure and paste it to a Word document named lab9.doc (or
lab9.docx).

Learning Activity #4: An Email-Enabled PHP Form for Submitting User Comments
1. In the X:\xampp\htdocs\myphp directory, use Notepad to create a new file named lab9_4.php with the

following contents:
<?php
if (!$_POST)
{
?>
A Web Form for Submitting User Comments Thru Email
<form action="<?=$_SERVER['PHP_SELF']; ?>" method="post">
<table width=90% align="center" style="font-size:12px">
<tr>
<td>Your name:</td>
<td><input type="TEXT" name="name" size=30></td>
</tr>
<tr>
<td>Your email:</td>
<td><input type="TEXT" name="email" size=30></td>
</tr>
<tr>
<td>Your gender:</td>
<td><input type="radio" name="gender" value="Male"> Male
<input type="radio" name="gender" value="Female"> Female
<input type="radio" name="gender" value="No given" checked>Not given </td>
</tr>
<tr>
<td>How you found us</td>
<td>
<select name="referrer">
<option value="Newspaper">Newspaper</option>
<option value="Magazine">Magazine</option>
<option value="County Fair">County Fair</option>
<option SELECTED value="other">Other</option>
</select>
</td>
</tr>
<tr>
<td>May we email you?</td>
<td><input type="checkbox" name="contact"
value="Y" CHECKED></td>
</tr>
<tr>
<td>Comments</td>
<td><textarea ROWS=4 COLS=50
name="comments"></textarea></td>
</tr>

PHP

153

</table>
<input type="submit" value="Submit">
</form>
<?php
}
else
{
if (!$_POST["name"]) { echo "Name is required!<br>"; }
if (!preg_match("/^[_a-z0-9-]+(\.[_a-z0-9-]+)*@[a-z0-9-]+(\.[a-z0-9]+)*$/i",$_POST['email']))
{ echo "Invalid email address!<br>"; }
else
{
echo "You have entered:\n
<form action='mailto:user@cis246.com?subject=user comments' method='post'
enctype='text/plain'>\n
<textarea name='Topic' rows=15 cols=90>";
echo
echo
echo
echo
echo
echo
echo

"User Comments\n";
"Name: ". $_POST["name"] . "\n";
"Email: ". $_POST["email"] . "\n";
"Gender: ". $_POST["gender"] . "\n";
"Referrer: ". $_POST["referrer"] . "\n";
"Contact: ". $_POST["contact"] . "\n";
"Comments: ". $_POST["comments"] . "\n";

echo "</textarea>\n
<input type='submit' value='Send Thru Email'>\n
</form>";
}
} // be sure to add this
?>

2.

Test the program with a Apache server (XAMPP).

3.

Capture a screen shot similar to the above figure and paste it to a Word document named lab9.doc (or
lab9.docx).

Learning Activity #5:


1. In the X:\xampp\htdocs\myphp directory, use Notepad to create a new file named lab9_5.php with the
following contents:

PHP

154

<?php
if ($_POST)
{
$err=array();
if
if
if
if
if
if
if

($_POST["first"]=="") { $err[]="First name is required!"; }


(empty($_POST["last"])) { $err[]="Last name is required!"; }
(!$_POST["address"]) { $err[]="Address is required!"; }
(!$_POST["Btype"]) { $err[]="Blood type is required!"; }
(!$_POST["subject"]) { $err[]="Check at least one class for next term!"; }
(!$_POST["payment"]) { $err[]="Specify the payment!"; }
(!$_POST["comment"]) { $err[]="Comment is required!"; }

if (count($err)>0) {
echo "Error(s) detected: <ol>";
foreach($err as $error) {
echo "<li>$error"; }
echo "</ol>";
}
else {
echo "You have entered:<ol>";
echo "<li> First Name: " . $_POST["first"];
echo "<li> Last Name: " . $_POST["last"];
echo "<li> Address: " . $_POST["address"];
echo "<li> Blood Type: " . $_POST["Btype"];
echo "<li> Subject:<ul>";
foreach($_POST["subject"] as $subject)
{ echo "<li>$subject"; }
echo "</ul>";
echo "<li> Payment: " . $_POST["payment"];
echo "<li> Comment: " . $_POST["comment"];
echo "</ol>";
}
}
else
{
?>
<form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post">
First Name: <input type="text" name="first"><br>
Last Name: <input type="text" name="last"><br>
Address: <input type="text" name="address" size=90><br>
<p>What is your blood type?
<input type="radio" name="Btype"
<input type="radio" name="Btype"
<input type="radio" name="Btype"
<input type="radio" name="Btype"

value="A">A.
value="B">B.
value="O">O.
value="AB">AB.

<p>What is/are class(es) you will take next term? (Check all that apply)<br>
<input type="checkbox" name="subject[]" value="CIS109">CIS109
<input type="checkbox" name="subject[]" value="CIS179">CIS179
<input type="checkbox" name="subject[]" value="CIS218">CIS218
<input type="checkbox" name="subject[]" value="CIS246">CIS246
<p>Payment method: <select name="payment">
<option value="COD">COD
<option value="Check">Check
<option value="Credit Card" selected>Credit Card
</select>

PHP

155

<p>Comment:<textarea name="comment" rows=5 cols=90></textarea>


<p><input type="submit" value="submit">
</form>
<?php
}
?>

2.

Test the program with a Apache server (XAMPP).

3.

Capture a screen shot similar to the above figure and paste it to a Word document named lab9.doc (or
lab9.docx).

Submitting the lab


1. Create a .zip file named lab9.zip containing:
Lab9_1.php
Lab9_2.php
Lab9_3.php
Lab9_4.php
Lab9_5.php
Lab9.doc (or .docx and make sure this file contains all the five screen shots)
2.

Upload the zipped file as response to question 11 or Assignment 9 (available in Blackboard).

PHP

156

Lecture #10

Handing File I/O

Introduction

Programmer frequently break codes into sections and save them as different files. There are many
reasons to explain about why programmers will do so, but the most important aspect is the reusability of codes. For example, in your PHP web-based site, each and every page must include a
privacy statement. A sophisticated PHP programmer will create a separated file, possibly called
"privacy.txt", and use a simple PHP code to include it with each PHP file. As you learn in previous
lecture, the include() or require() functions will do it.
<?php
include("privacy.txt");
?>

Use PHP to open files and manipulate the data contained within them is indeed a good way to
manage PHP codes and increase the code re-usability. PHP thus provides many built-in file
processing functions with options of access control to give you flexibility to store information
across requests.
In PHP, file implementation offer the chance to easily and permanently store information across
scripts, however, files are good for storing small bits of information and they are not as flexible as
databases by any means.
Working
With Files in
PHP

PHP is a server-side scripting language, which means it can only be processed by the server.
Consequently, work with files in PHP's terms actually refer to file processing on the server-side
instead of the client machine. This could cause some problems.
If you are not the server administrator or you don't have the administrator privilege, you may not be
given the right to upload files or dynamically change file contents using PHP code. In plain
English, this means you will probably see error codes when using PHP script to deal with files
stored on the server.
As a new comer to PHP files, consider using the following functions to check the files access
control status to avoid getting errors when you try to work with a file to which you have no
permissions.
The is_readable(), is_writeable(), is_executable(), is_file(), and is_dir() functions
These functions takes a string as its only parameter and either return true or false. Naturally,
is_readable() will return true if the string parameter is readable. The is_dir() function will return
false if the parameter is not a directory. For example:
<?php
$str="8_1.php";
if(is_readable($str)) { echo "$str is readable!"; }
if(is_writeable($str)) { echo "$str is writable!"; }
if(is_executable($str)) { echo "$str is executable!"; }
if(is_file($str)) { echo "$str is a file!"; }
if(is_dir("../chp8")) { echo "chp8 is a directory!"; }
?>

Checking whether a file exists


Before you can use PHP to work with or utilize a file, you should first make sure the file exists. Use
the file_exists() function to check whether a file or directory exists. For example:
<?php
// clear file status cache
clearstatcache();

PHP

157

$filename = "apple.txt";
if (file_exists($filename)) {
echo "The $filename file exists!<br>";
} else {
echo "The $filename file does not exist!<br>";
}
$dirname = "test";
if (file_exists($dirname)) {
echo "The $dirname directory exists!<br>";
} else {
echo "The $dirname directory does not exist!<br>";
}
?>

Operating systems may cache the files and directories, so when you use the file_exists() function to
check the file or directory existence, you may be fooled by the system cache. To avoid this, call the
clearstatcache() function to clear file status cache.
Reading files - The readfile(), file(), and file_get_contents() functions
In addition to the include() and require() functions, readfile(), file(), and file_get_contents()
functions can open and display files.
The readfile() function takes a filename as its first parameter and simply opens the file, outputs it to
the screen, then closes it. For example, assume that the "apple.txt" file already exists, readfile() will
attempt to open it, read it all into memory, and then output it. The function readfile() will return
false, if unsuccessful.
<?php
readfile("apple.txt");
?>

Like include() and require(), you have absolutely no control over the text that comes out when using
the readfile() function. You should use readfile() when you just want to print a file out without any
further action.
The file() and file_get_contents() functions are very similar, but file() returns an array, while
file_get_contents() loads the file specified as the first parameter and returns it as a string. For
example, assume that the apple.txt file has at least two lines of content. Use the code below to
display the contents of the file.
<?php
$str1 = file("apple.txt");
foreach ($str1 as $line) {
echo $line . "<br>";
}
echo "--------------------------<br>";
$str2 = file_get_contents("apple.txt");
echo $str2 . "<br>";
?>

The results looks like:


Apple
orange

PHP

158

banana
-------------------------Apple orange banana

Note: file() and file_get_contents() do not output any data. Instead, they will return the contents of
the file as string, so you need to declare variables to hold the string values.
With the file() each line in the file is returned as an element, while file_get_contents() simply read
the contents of a file into a string.
The fopen() function
The acronym fopen stands for "file open". It is used to access a file (or a remote file) with
predefined file access permissions. The fopen() function syntax is:
fopen(filename, access mode)

If PHP detects that filename specifies a local file, then it will try to open it and read its contents;
therefore, the file must be accessible to PHP. You need to ensure that the file access permissions is
set properly. If you enable the file in safe mode or use open_basedir() function, further restrictions
may apply. In the following example, "apple.txt" is the file to be opened, "r" is the file access
permission pointer means read-only. Notice that the apple.txt must exist before you execute the
following script.
<?php
$str = fopen("apple.txt", "r");
echo $str;
?>

The fopen() function only opens the file and apply the specified access control to it, but it does not
do anything more. In PHP, fopen() creates a file handle ($str represents the file handle), if the file is
successfully opened. You then need to call other functions to read, write, execute, or delete the file
once the file handle has been created by the fopen() function. To read from a file, the function
fread() is used and to write to a file fwrite() is used.
At this moment, the output of the above code will look something similar to:
Resource id #2

and it's obviously an ID of the file handle.


According to the PHP manual, there are 6 major file access modes:
Mode Description
r
Opens for reading only from the beginning of the file.
r+
Opens for reading and writing from the beginning of the file.
w
Opens for writing only; overwrites the old file if one already exists.
w+
Opens for writing and reading; overwrites the old file if one already exists.
a
Opens for writing only and appends new data to the end of the file.
a+
Opens for reading and writing at the end of the file.
There is also a seventh option, "b", which opens the file in binary mode.
If PHP detectes that filename specifies a file transfer protocol (such as FTP, or HTTP) and the path
is a valid URL, PHP will attempt to open and read the remote file. Again, you must make sure that
allow_url_fopen is enabled. If the file cannot be opened, fopen() returns false. If the file is
successfully opened, a file handle is returned and you can proceed.
Note that different operating system families have different line-ending conventions. When you
PHP

159

write a text file and want to insert a line break, you need to use the correct line-ending character(s)
associated with your operating system. Unix based systems use \n "as the line ending character
Windows based systems use \r\n as the line ending characters and Macintosh based systems use
\r as the line ending character.
The fread() and fgets() functions
In PHP, there are two (2) functions that you can use to read in a file, fgets() and fread(). The fread()
function contains two (2) parameters: a file handle to read from and the number of bytes to
read. For example:
<?php
$str = fopen("apple.txt", "r");
// display the first 12 bytes
echo fread($str, 12);
?>

Counting the file size in bytes is not easy, but do not worry about too much about it. You can use
the filesize() function to check and return the file size in bytes. For example:
<?php
$str = fopen("apple.txt", "r");
echo fread($str,filesize("apple.txt"));
?>

Creating and changing files


In PHP, there are two (2) functions available for you to create file and change file contents,
file_put_contents() and fwrite().
The file_put_contents() function
The file_put_contents() function writes a string to a file. It is the combination of fopen(), fwrite()
and fclose(), all in one function. Calling the file_put_contents() is identical to calling fopen(),
fwrite(), and fclose() consequetively.
It takes two parameters, the filename to write to and the content to write respectively, with a third
optional parameter specifying extra flags which we will get to in a moment. If file_put_contents()
is successful, it returns the number of bytes written to the file, otherwise it will return false.
For example:
The fwrite() function
The fwrite() function takes a string to write as a second parameter and an optional third parameter
where you can specify how many bytes to write. If you do not specify the third parameter, all of the
second parameter is written out to the file, which is often what you want. See the following
example:
<?php
$handle = fopen("apple.txt", "wb");
$wrt = fwrite($handle, "I am learning PHP!");
fclose($handle);
?>

In this example, a variable $handle is the file handle representing the opened apple.txt file.
Additionally the fopen() is called with "wb" as the second parameter, which means "write-only,
binary-safe". Always use "b" to ensure compatibility with Windows servers.
$wrt is the file handle for storing $handle (which represents apple.txt). The fwrite() function will
then write "I am learning PHP!" to the apple.txt file.

PHP

160

Note again that fclose() is immediately called after, to close the file. This is a best practice in terms
of security.
Moving, copying, and deleting files
In PHP, files are moved using rename(), copied using copy(), and deleted using unlink().
The rename() function
This rename() function takes two parameters: the original filename and the new filename you wish
to use. Rename() can rename/move files across directories and drives, and will return true on
success or false otherwise. For example, to change file name of an existing file from apple.txt to
apple.txt.bak. You can use the following code:
<?php
$filename="apple.txt";
$filename2 = $filename . '.bak';
rename($filename, $filename2);
?>

Notice that rename() should be used to move ordinary files and not files uploaded through a form.
The reason for this is because there is a special function, called move_uploaded_file(), which
checks to make sure the file has indeed been uploaded before moving it - this stops people trying to
hack your server into making private files visible. You can perform this check yourself if you like
by calling the is_uploaded_file() function.
The copy() function
The copy() function takes two parameters: the filename you wish to copy from, and the filename
you wish to copy to. The difference between rename() and copy() is that calling rename() results in
the file being in only one place, the destination, whereas copy() leaves the file in the source location
as well as placing a new copy of the file into the destination.
For example, to copy a non-empty file apple.txt to orange.txt, use:
<?php
copy("apple.txt","orange.txt");
?>

The PHP engine will duplicate the apple.txt file but name the duplication orange.txt. Therefore, both
apple.txt and orange.txt will be stored on the system. Notice that, due to the operating systems
settings and type of operating systems, this copy() function may or may not copy empty (zerolength) files. If you encounter this problem, simply use the touch() function to handle non-empty
file.
The unlink() and rmdir() function
To delete files using PHP code, simply pass a filename string as the only parameter to unlink().
Note that unlink() deals only with files. If you wish to delete a directory, you need the rmdir()
function. For example, assume both a file called empty.txt file and the directory test exists.
<?php
unlink("empty.txt");
rmdir("test");
?>

Note: If you have a file opened with fopen(), you need to fclose() it before you call unlink().
The feof() function
In programming languages, EOF is an acronym for End-Of-File, feof() is thus a function that
determine whether or not PHP engine has reached the end of a file when reading it. It returns TRUE
if the file pointer is at EOF or an error occurs including socket timeout; otherwise returns FALSE.
PHP

161

The syntax for the feof() function is:


feof(int)

Handling file
uploading

With PHP's ability to handle file uploads, your web site will be fabulous. The basis for file uploads
lies in a special variety of HTML input element, "file", which brings up a file selection dialog in
most browsers that allows your visitor to select a file for uploading. For example:
<input name="assignment1" type="file">

Also, the file encryption type must be "multipart/form-data". For example:


<form enctype="multipart/form-data" method="post" action="filename.php">
The function that handles file uploading is move_uploaded_file(). Its syntax is:
move_upload_file(filename, destination)

According to PHP manual (available at http://us3.php.net/features.file-upload), PHP uses the


$_FILE global variable to store all the uploaded file information. However, $_FILE handles the
uploading file information in an array. Given the following HTML form,
<form enctype="multipart/form-data" action="upload.php"
method="post">
<input type="hidden" name="MAX_FILE_SIZE" value="30000">
Upload file: <input type="file" name="userfile" size="20">
<input type="submit" value="Upload">
</form>

The hidden field with the name "MAX_FILE_SIZE" must exist and must precede the file input field
to specify the maximum filesize in bytes (8 bits in one byte).
Use the following multidimensional array values to handle file uploading. userfile is the name of the
file field.
$_FILES['userfile']['name']: The original name of the file on the client machine.
$_FILES['userfile']['type']: The MIME type of the file; if the browser provided this information.
An example would be "image/gif".
$_FILES['userfile']['size']: The size, in bytes, of the uploaded file.
$_FILES['userfile']['tmp_name']: The temporary filename of the file in which the uploaded file
was stored on the server.
$_FILES['userfile']['error']: The error code associated with this file upload.
To process the file upload, you need to use the move_upload_file() function with the above
multidimensional array values. For example:
<?php
$uploadDir = "PathForUpload";
$uploadFile = $uploadDir . $_FILES['userfile']['name'];
if (move_uploaded_file($_FILES['userfile']['tmp_name'],
$uploadFile))
{
echo "Upload succeeded!";
}
else
{
echo "Upload failed!";
}
?>

PHP

162

Notice that PathForUpload is the path to the directory that you want to the uploaded file to be
stored. $_FILE['userfile']['size'] check the file size and throw away files that exceeds the limits.
$_FILES['userfile']['type'] variable to throw away any files that didn't match a certain type criteria,
but use this only as first of a series of checks, because this value is completely under the control of
the client and not checked on the PHP side.
If no file is selected for upload in your form, PHP will return the following:
$_FILES['userfile']['size'] as 0, and
$_FILES['userfile']['tmp_name'] as none.

Review
Questions

1. Which PHP function cannot include and evaluate the lab.txt file?
A. include("lab.txt")
B. fopen("lab.txt")
C. required ("lab.txt")
D. All of the above
2. Assuming that lab.txt is a read-only text file, which is the correct output of the following code?
<?php
$filename = 'lab.txt';
if (is_readable($filename)) { echo 'A'; } else {echo 'D'; }
if (is_writable($filename)) { echo 'B'; }
if (is_executable($filename)) { echo 'C'; }
?>
A. A
B. B
C. C
D. D
3. Which loads the lab.txt file and returns it as a string?
A. file("lab.txt");
B. file_get_contents("lab.txt");
C. fopen("lab.txt");
D. readfile("lab.txt");
4. Which option of the fopen() function opens a text file for reading and writing from the beginning
of the file?
A. r
B. rw
C. r+
D. rw+
5. In PHP, which function can create file and change file contents?
A. fwrite()
B. fcreate()
C. fopen()
D. fnew()
6. In PHP, if you want to copy an file named old.txt to another named new.txt, you can use __.
A. <?php cp("old.txt", "new.txt") ?>
B. <?php copy("old.txt", "new.txt") ?>

PHP

163

C. <?php cp("new.txt", "old.txt") ?>


D. <?php copy("new.txt", "old.txt") ?>
7. In PHP, which command removes a file named lab.txt?
A. remove("lab.txt")
B. delete("lab.txt")
C. unlink("lab.txt")
D. clear("lab.txt)
8. Which is the correct encryption type you must use when handling PHP file uploading?
A. text/plain
B. MIME/www-form-upload
C. application/x-www-form-urlencoded
D. mutlipart/form-data
9. Which displays the MIME type of the file if the browser provided this information?
A. $_FILES['userfile']['type']
B. $_FILES['userfile']['mtype']
C. $_FILES['userfile']['mime']
D. $_FILES['userfile']['mime_type']
10. In PHP, the __ function determines whether or not PHP engine has reached the end of a file
when reading it.
A. end_of_file()
B. file_end()
C. end()
D. feof()

PHP

164

Lab #10

Handling File I/O

Learning Activity #1: Write user entry to a file


1. In the X:\xampp\htdocs\myphp directory (create the myphp subdirectory if it does not exist), use Notepad
to create a blank text file named apple.txt.
2. Create a new file named lab10_1.php with the following contents:
<?php
if ($_POST)
{
$message=$_POST["message"];
$handle = fopen("apple.txt", "wb");
$wrt = fwrite($handle, $message);
fclose($handle);
echo "The file has been modified to: <hr>";
include("apple.txt");
}
else
{
?>
<form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post">
Write a sentence: <input type="text" name="message" size=90>
<br><input type="submit" value="Submit">
</form>
<?php
}
?>

3.

Test the lab10_1.php, and then check the contents of the apple.txt file. The user entries will be written to the
apple.txt file.

4.

Capture a screen shot similar to the above figure and paste it to a Word document named lab10.doc (or
lab10.docx).

Learning Activity #2: Write user entries to a file and create a copy with a time-stamped filename
1. In the X:\xampp\htdocs\myphp directory, use Notepad to create a new file named lab10_2.php with the
following contents:
<?php
if ($_POST)
{
$message=$_POST["message"];
$handle = fopen("apple.txt", "wb");
$wrt = fwrite($handle, $message);
fclose($handle);
include("apple.txt");
}
if ($_POST)

PHP

165

{
$message=$_POST["message"];
// duplicate the apple.txt file and name it apple.bak
copy("apple.txt","apple.bak");
// write user-entries to apple.txt
$handle = fopen("apple.txt", "wb");
$wrt = fwrite($handle, $message);
fclose($handle);
echo "the file has been modified to: <hr>";
//display the modified apple.txt
include("apple.txt");
// rename apple.txt by adding a time-stamp to the file name
/* date('MdY-His') will display current date and
time in MonDDYYYY-HHMMSS format. */
$newname="apple" . date('MdY-His') . ".txt";
rename("apple.txt",$newname);
// delete modified apple.txt if any
unlink("apple.txt");
// rename apple.bak to apple.txt so apple.txt returns to its origin
rename("apple.bak","apple.txt");
}
else
{
?>
<form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post">
Write a sentence: <input type="text" name="message" size=90>
<br><input type="submit" value="Submit">
</form>
<?php
}
?>

2.

Test the program with a Apache server (XAMPP). Verify the file renaming, copying, and deleting on the server
side.

3.

Capture a screen shot similar to the above figure and paste it to a Word document named lab10.doc (or
lab10.docx).

Learning Activity #3: Checking file and directory status


1. In the X:\xampp\htdocs\myphp directory, use Notepad to create a new file named lab10_3.php with the
following contents:
<?php
// check file access status

PHP

166

$str="lab10_1.php";
if(is_readable($str)) { echo "$str is readable!<br>"; }
if(is_writeable($str)) { echo "$str is writable!<br>"; }
if(is_executable($str)) { echo "$str is executable!<br>"; }
if(is_file($str)) { echo "$str is a file!<br>"; }
if(is_dir("../chp8")) { echo "chp8 is a directory!<br>"; }
// clear file status cache
clearstatcache();
$filename = "apple.txt";
if (file_exists($filename)) {
echo "The $filename file exists!<br>";
} else {
echo "The $filename file does not exist!<br>";
}
$dirname = "test";
if (file_exists($dirname)) {
echo "The $dirname directory exists!<br>";
} else {
echo "The $dirname directory does not exist!<br>";
}
?>

2.
3.

Test the program with a Apache server (XAMPP).


Test the script. It should look like:

4.

Capture a screen shot similar to the above figure and paste it to a Word document named lab10.doc (or
lab10.docx).

Learning Activity #4: Site Hit Counter


1. In the X:\xampp\htdocs\myphp directory, use Notepad to create a text file named count.txt with only the
following digit (zero) as content:
0
2.

Create a new file named lab10_4.php with the following contents:


<?php
// open the count.txt file for reading
$handle = fopen("count.txt","r");
// read the value
$count = fread($handle, filesize("count.txt"));
// close the file handle

PHP

167

fclose($handle);
// increment by 1
$count++;
// display the hit count
echo "This page has been visited $count times";
// open the count.txt file for writing
$handle = fopen("count.txt","w");
//write new value to count.txt
fwrite($handle, $count);
// close the file handle
fclose($handle);
?>
3.

Test the lab10_4.php script. You should see the following sentence with an increasing value of n.

4.

Capture a screen shot similar to the above figure and paste it to a Word document named lab10.doc (or
lab10.docx).

Learning Activity #5: Uploading Files to server


1. In the X:\xampp\htdocs\myphp directory, use Notepad to create a new file named lab10_5.php with the
following contents:
<?php
if ($_POST)
{
/* part of the code are adopted from PHP manual */
$uploadDir = './test/';
$uploadFile = $uploadDir . $_FILES['userfile']['name'];
print "<pre>";
if (move_uploaded_file($_FILES['userfile']['tmp_name'], $uploadFile))
{
echo "File was successfully uploaded. ";
echo "Here's some more info:\n";
echo _r($_FILES);
}
else
{
echo "Possible file upload attack! Here's some info:\n";
echo _r($_FILES);
}
print "</pre>";
}
else

PHP

168

{
?>
<form enctype="multipart/form-data" method="post"
action="<?=$_SERVER['PHP_SELF']; ?>">
<input type="hidden" name="MAX_FILE_SIZE" value="100000" />
Choose a file to upload: <input name="userfile" type="file" />
<input type="submit" value="Upload File" />
</form>
<?php
}
?>

2.
3.

Test the program with a Apache server (XAMPP).


Create a new directory name test as a subdirectory to whatever directory the lab10_5.php resides. For
example, if the path of lab10_5.php is ....../chp10/8_5.php, then the path of test is ...../chp10/test.
Test the script. You will need to change to the test directory (and possibly refresh the page) to view the
uploaded files.

4.

Capture a screen shot similar to the above figure and paste it to a Word document named lab10.doc (or
lab10.docx).

Submitting the lab


1. Create a .zip file named lab10.zip containing:
Lab10_1.php
Lab10_2.php
Lab10_3.php
Lab10_4.php
Lab10_5.php
Lab10.doc (or .docx and make sure this file contains all the five screen shots)
2.

Upload the zipped file as response to question 11 or Assignment 10 (available in Blackboard).

PHP

169

Lecture #11

PHP Cookies and Sessions

What are
cookies?

A cookie is a tiny file inserted onto a web clients hard drive (or in RAM) which contains data that
web server detected and stored. When creating cookies, the programmer specifies how long s/he
wants the cookie to be valid for, and once done, the cookie remains in place until that date, then it
expires.
Cookies automatically send the data they store to the web server (and received/parsed by server-side
script like PHP, Perl) each time when the user visits the web server. That means that once the web
server places a cookie on the clients machine, our visitors browser will automatically send the
contents of that cookie across to the web server each time they visit the web site.
Note that some clients specifically configure their browser to reject cookies, believing that cookies
are malicious. Theres nothing the programmer can do in this case. It is also important to note that
sessions only last till the user closes their browser, whereas cookies can be configured to last longer.
However, other than the above, there is not much difference between session data and cookie data
for most purposes.

The
setcookie()
function

The setcookie() function defines a cookie to be sent along with the rest of the HTTP headers. Like
other headers, cookies must be sent before any output from your script (this is a protocol
restriction). This requires that you place calls to this function prior to any output, including and tags
as well as any whitespace. If output exists prior to calling this function, setcookie() will fail and
return FALSE. If setcookie() successfully runs, it will return TRUE. This does not indicate whether
the user accepted the cookie or not.
The setcookie() function syntax is:
setcookie(name, value, expire, path, domain, secure)

All the parameters except the name argument are optional. You may also replace an argument with
an empty string ("") in order to skip that argument. Because the expire argument is integer, it cannot
be skipped with an empty string, use a zero (0) instead.
Table 1. Explanation of the setcookie() parameters
Parameter
name
value

expire

path

domain

PHP

Description
The name of the cookie.
The value of the cookie. This
value is stored on the clients
computer; do not store sensitive
information.
The time the cookie expires.
This is a Unix timestamp so is in
number of seconds since the
epoch. In other words, you'll
most likely set this with the
time() function plus the number
of seconds before you want it to
expire or you might use
mktime().
The path on the server on which
the cookie will be available.

The domain that the cookie is

170

Examples
'cookiename' is called as $_COOKIE['cookiename']
Assuming the name is 'cookiename', this value is
retrieved through $_COOKIE['cookiename']

time()+60*60*24*30 will set the cookie to expire in 30


days. If not set, the cookie will expire at the end of the
session (when the browser closes).

If set to '/', the cookie will be available within the entire


domain. If set to '/foo/', the cookie will only be available
within the /foo/ directory and all sub-directories such as
/foo/bar/ of domain. The default value is the current
directory in which the cookie is being set.
To make the cookie available on all subdomains of

available.

secure

Indicates that the cookie should


only be transmitted over a secure
HTTPS connection. When set to
TRUE, the cookie will only be
set if a secure connection exists.
The default is FALSE.

example.com you set it to '.example.com'. The . is not


required but makes it compatible with more browsers.
Setting it to www.example.com will make the cookie
only available in the www subdomain.
0 or 1

For example, the following code will insert a cookie named something like user@cis246[1].txt
(file name are subject to conditions) in the Documents and Settings directory of the user's home
drive (usually C:\).
<?php
$str = "You visited my CIS246 site!";
// set a simple cookie with expiration
setcookie("cis246_01", $str, time()+3600);
?>
<p>I have just set 1 cookie in your local drive!</p>

Here's a small reference regarding the expire parameter and the amount of time they signify in
determining the expiration date/time of a cookie:
One Minute: 60
Ten Minutes: 600
Half-an-Hour: 1800
One Hour: 3600
One Day: 86400
One Week: 604800
Two Weeks: 1209600
One Month (30 days): 2592000
One Year (365 days): 31536000

When the user finds the cookie file and opens it using Notepad, it will look similar to (possibly all
in one line):
cis246_01
You+visited+my+CIS246+site%21
business.cypresscollege.edu/cis246/
1536
851593344
29747786
3595659008
29747777
*

Reading
cookies
from server

Once the cookies have been sent to the client computer, they can be accessed on the next web page
load with the $_COOKIE or $HTTP_COOKIE_VARS arrays from the remote server. However,
cookies will not become visible until the next loading of a web page for which the cookie should be
visible. Notice that Microsoft Windows sometimes has a problem accepting the
$HTTP_COOKIE_VARS global variable. Using $_COOKIE is preferred. For example:
<?php
// Print an individual cookie
echo $_COOKIE["cis246_01"] . "<hr>";
echo $HTTP_COOKIE_VARS["cis246_01"];

PHP

171

To test if a cookie was successfully set, check for the cookie on a next loading of the web page
before the cookie expires. Expire time is set via the expire parameter. A nice way to debug the
existence of cookies is by simply calling print_r($_COOKIE). For example:
<?php
// view all cookies
print_r($_COOKIE);
?>

Deleting
(Destroying)
a cookie

Finally, you may wonder how you delete this cookie when you do not want it any more. Well, PHP
has a solution for that too! Just place a new setcookie() statement with the variable you want to
deconstruct. For example, if you want to deconstruct the "cis246" cookie do the following:
<?php
setcookie("cis246");
//deletes the cookie
?>

Sample
Usage of
cookies

Cookies may be used to store users preferences locally. In the following PHP code, the HTML
form will check the user to enter either a color name (e.g. red) or a color code (e.g. #ccffee).
Then, the setcookie method will store the value in the ColorCookie cookie. The / sign indicates
that the cookie will be available within the entire domain example.com.
<?php
if ($_POST) {
$color = $_POST["color"];
setcookie("ColorCookie", $color);
setcookie("ColorCookie", $color, time()+3600); /* expire in 1 hour
*/
setcookie("ColorCookie", $color, time()+3600, "/", ".example.com",
1);
}
else
{
?>
<center>
<form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post">
Enter a color: <input type="text" name="color" size="20"> (e.g.
"red" or "#ff00cc")
<input type="Submit" value="Submit">
</form>
</cetner>
<?php
}
?>

The next code will retrieve the cookie values and use it as the background color of the web page.
<html>
<body bgcolor="<?php echo $_COOKIE['ColorCookie']; ?>"></body>
<hr size=5 color="<?php echo $HTTP_COOKIE_VARS['ColorCookie']; ?>"
width=100%>

PHP

172

</html>

Starting a
Session

Session management is a mechanism to maintain state about a series of requests from the same user
across some period of time. That is, the term "session" refers to the time that a user is at a particular
web site. It is the way to associate data with a user during a visit to a Web page. For example, a
typical online shopping session might include logging in, putting an item into the shopping cart,
going to the checkout page, entering address and credit card data, submitting the order, and closing
the browser window.
A visitor accessing your web site is assigned a unique id, the so-called session id. This is either
stored in a cookie on the user side or is propagated in the URL. Session support in PHP consists of a
way to preserve certain data across subsequent accesses. This enables you to build more customized
applications and increase the appeal of your web site.
A PHP session is started either:
explicitly by session_start(), or
implicitly by registering a variable for the session using session_register().
You can call session_start() on top of the page, so that session variables are available to your script.
You then register variables to the session in the script. For example,
<?php
session_start();
// Use of session_register() is deprecated
$barney = "A big purple dinosaur.";
session_register("barney");
// Use of $_SESSION is preferred, as of PHP 4.1.0
$_SESSION["zim"] = "An invader from another planet.";
?>

If session_start() was not called before this function is called, an implicit call to session_start() with
no parameters will be made. $_SESSION does not mimic this behavior and requires session_start()
before use. For example, in the code below you can create a session and register a variable with a
value
<?php
//file1.php
// start the session
session_start();
// register a variable and assign a value to it
$_SESSION["starting_time"] = date("h:i:s");
echo "<a href='file2.php'>Next";
?>

Create a second file that will accept the session data passed by the file1.php.
<?php
//file2.php
// start the session
session_start();
echo "You start the exam at " . $_SESSION["starting_time"];

PHP

173

session_destroy();
?>

The session_destroy() function destroys all of the data associated with the current session. It does
not unset any of the global variables associated with the session, or unset the session cookie.
Registering a session variable is done through session_register(). This allows you to create (or
register) variables which are stored throughout the session, which can be referred to during the
session. All variables you want to preserve across page requests must be registered to the session
library with the session_register() function. Note that this function takes the name of a variable as
argument, not the variable itself. You can use session_unregister() to remove variables from the
session. For example:
<?php // old format for PHP4 and earlier version
session_register("count");
$count=0;
$count++;
session_unregister("count");
?>
<p>You have seen this page at least <?php echo $count; ?>
times.</p>
<p><A HREF="http://www.cnn.com?<?=SID?>">Continue.</A></p>

However, both the session_register and session_unregister() methods have been DEPRECATED
as of PHP 5.3.0 and REMOVED as of PHP 5.4.0. With PHP5, you need to use $_SESSION to
replace session_register and unset to replace session_runregister. For example,
<?php // new format for PHP5 and later
$_SESSION['count'] = 1; ?>
<p>You have seen this page at least <?php echo
$_SESSION['count']; ?> times.</p>
<p><A HREF="http://www.cnn.com?<?=SID?>">Continue.</A></p>
<?php unset($_SESSION['count']); ?>

PHP4 also provided the session_is_registered method to find out whether a global variable is
registered in a session. For example,
// check if the "count" session does not exists already
if (!session_is_registered("count"))
{
$_SESSION['count'] = 0;
$_SESSION['start'] = time();
}

However, the session_is_registered method has been DEPRECATED as of PHP 5.3.0 and
REMOVED as of PHP 5.4.0. With PHP5, you need to use:
if( !isset($_SESSION["count"]) )
{
$_SESSION['count'] = 0;
$_SESSION['start'] = time();
}

PHP

174

The session_name() method returns the name of the current session. If name is given,
session_name() will update the session name and return the old session name. Notice that the
session name can't consist of digits only, at least one letter must be present. Otherwise a new session
id is generated every time.
<?php
// set the session name to CIS246
session_name("CIS246");
session_start();
echo session_name("CIS246");;
?>

The output is:


CIS246

Cookies vs.
Sessions

Both cookies and sessions are available to you as a PHP developer, and both accomplish much the
same task of storing data across pages on your site. However, there are differences between the two
that will make each favorable in their own circumstance.
Cookies can be set to a long lifespan, which means that data stored in a cookie can be stored for
months, if not years. Cookies, having their data stored on the client, work smoothly when you have
a cluster of web servers, whereas sessions are stored on the server, meaning in one of your web
servers handles the first request, and the other web servers in your cluster will not have the stored
information.
Sessions are stored on the server, which means clients do not have access to the information you
store about them - this is particularly important if you store shopping baskets or other information
you do not want you visitors to be able to edit by hand by hacking their cookies. Session data, being
stored on your server, does not need to be transmitted with each page; clients just need to send an
ID and the data is loaded from the local file. Finally, sessions can be any size you want because they
are held on your server, whereas many web browsers have a limit on how large cookies can be. This
is doneto stop rogue web sites from chewing up gigabytes of data with meaningless cookie
information on your computer.

Review
Questions

1. Which is a simple script that you should place at the beginning of your PHP code to start up a
PHP session?
A. <?php session_begin(); ?>
B. <?php session_start(); ?>
C. <?php session_open(); ?>
D. <?php session_set(); ?>
2. Given the following code, the output is __.
<?php
session_start();
$_SESSION['cis246'] = 1;
echo $_SESSION['cis246'];
?>
A. cis246
B. $_SESSION['cis246']
C. 1
D. no output

PHP

175

3. You can completely destroy the session entirely by calling the __ function.
A. session_close();
B. session_delete();
C. session_remove();
D. session_destroy();
4. Which sets a PHP session name to cis246?
A. session_name("cis246");
B. session_set("cis246");
C. session_start("cis246");
D. session_open("cis246");
5. You can register a session by issuing __.
A. register("cis246");
B. session_register("cis246");
C. register_session("cis246");
D. session_start_register("cis246");
6. A cookie is usually sent from the web server to the client in the __ header field as part of an
HTTP response.
A. Content-Type: Set-Cookie
B. Content-Type: Cookie_Set
C. Set-Cookie
D. Cookie_Set
7. Given the following code segment, __.
<pre>setcookie("start", $start, time()+600, "/", "", 0);</pre>

A. start is the name of the cookie


B. the value of cookie is held by the $start variable
C. the cookie expires in 10 minutes
D. all of the above
8. __ defines a cookie to be sent along with the rest of the HTTP headers.
A. setcookie()
B. start_cookie()
C. cookie_start()
D. cookie_set()
9. Which can delete a cookie named "cis246"?
A. deletecookie("cis246", "", time()+3600);
B. setcookie("cis246", "", time()+3600);
C. setcookie("cis246", "", time()-3600);
D. deletecookie("cis246", "", time()-3600);
10. The PHP __ variable is used to retrieve a cookie value.
A. $_POST
B. $_GET
C. $_COOKIE
D. $_READ

PHP

176

Lab #11

PHP Session and cookie

Learning Activity #1: Create a client-side hit counter


1. In the X:\xampp\htdocs\myphp directory (create the myphp subdirectory if it does not exist), use Notepad
to create a new file named lab11_1.php with the following contents:
<?php
// using cookie
if ($_COOKIE["visits"] == "") {
$count = 0;
}
else
{
$count = $_COOKIE["visits"];
$count++;
}
setcookie("visits", $count);
print "<p>You visited this site <b>$count</b> times.";
// using session
session_start();
print "<p>You visited this site <b>$count</b> times in this session.";
?>

2.

Test the program with a Apache server (XAMPP) by refreshing the page and visiting this page back and forth.
A sample output looks like:

3.

Capture a screen shot similar to the above figure and paste it to a Word document named lab11.doc (or
lab11.docx).

Learning Activity #2: Create a session to store user data temporarily


1. In the X:\xampp\htdocs\myphp directory, use Notepad to create a new file named lab11_2.php with the
following contents:
<?php
if ($_POST)
{
session_start();
$_SESSION["fullname"] = $_POST["fullname"];
echo "Welcome " . $_SESSION["fullname"] . "!<br>";
echo "<a href=lab11_2_1.php>Next Page</a>";
}
else
{
?>

PHP

177

<form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post">


What is your name?
<input type="text" name="fullname">
<input type="submit" value="Go">
</form>
<?php
}
?>

2.

In the X:\xampp\htdocs\myphp directory, use Notepad to create a new file named lab11_2_1.php with the
following contents:
<?php
session_start();
echo "User Name: " . $_SESSION["fullname"];
echo " | <a href=' lab11_2_2.php'>Next</a>";
echo "<iframe src='http://www.pbs.com' width=100%></iframe>";
?>

3.

Create a new file named lab11_2_2.php with the following contents:


<?php
session_start();
echo "I still know your user Name: " . $_SESSION["fullname"];
echo " | <a href=' lab11_2_1.php'>Previous</a>";
echo "<iframe src='http://www.att.com' width=100%></iframe>";
//destroys all data registered to a session
session_destroy();
?>

4.

Test the scripts by entering your full name, and then click the hyperlinks. With the user entry, the second and
third pages will magically contain the session data. Notice that, when you click the "previous" hyperlink,
session_destroy() delete all data registered to this session, so you WILL NOT see your name any more.
Depending on the server settings, you may see an error message similar to "PHP Notice: Undefined index:
fullname in .........\ lab11_2_1.php on line 4" meaning you the session data no longer exists.

to
5.

to

to

Capture a screen shot similar to the above figure and paste it to a Word document named lab11.doc (or
lab11.docx).

Learning Activity #3: Use PHP session to time user activity


1. In the X:\xampp\htdocs\myphp directory, use Notepad to create a new file named lab11_3.php with the
following contents:
<?php
session_start();
$sessionId = session_id();
if(!isset($_SESSION["count"]) )
{

PHP

178

$_SESSION['count'] = 0;
$_SESSION['start'] = time();
}
else {
$_SESSION['count'] = $_SESSION['count'] + 1;
}
?>
<html><body>
<p>This page is in the session of <b>(<?=$sessionId?>)</b>.</p>
<p>You visited this site <?=$_SESSION['count']?> times.</p>
<p>This session has lasted <?php echo (time() - $_SESSION['start']); ?> seconds.
</body></html>

2.

Test the program with a Apache server (XAMPP). A sample output looks:

3.

Capture a screen shot similar to the above figure and paste it to a Word document named lab11.doc (or
lab11.docx).

Learning Activity #4: Web site access control using PHP session.
1. In the X:\xampp\htdocs\myphp directory, use Notepad to create a new file named lab11_4.php with the
following contents:
<?php
if ($_POST) {
$uid=$_POST["uid"];
$psd=$_POST["psd"];
if (($uid=="jsmith" && $psd=="cis246") || ($uid=="akwu012" && $psd=="cis246") )
{
echo "You are authorized to visit <a href='http://www.pbs.com'>PBS</a> site.";
session_start();
$_SESSION['uid'] = $uid;
$_SESSION['access'] = "yes";
}
else
{
echo "You are not authorized!";
}
}
else
{
?>
<html>
<body>
<center>
<form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post">

PHP

179

User ID: <input type="text" name="uid" size="20"><BR>


Password: <input type="password" name="psd" size="20"><BR>
<input type="Submit" value="Submit">
</form>
</center>
</body>
</html>
<?php
}
?>

2.

Test the program by entering correct and incorrect combinations of username and password.

to
3.

Capture a screen shot similar to the above figure and paste it to a Word document named lab11.doc (or
lab11.docx).

Learning Activity #5:


Note: This piece of code will verify that the user input matches the valid credentials. If there is a valid match, a
cookie is created holding the encrypted login information, if there is no match, a flag is set to indicate a login error.
1.

In the X:\xampp\htdocs\myphp directory, use Notepad to create a new file named lab11_5.php with the
following contents:
<?php
$username = 'cis407';
$password = 'sapphire';
$time=time();

Define default user


name and password

if ($_POST)
{
if ($_POST[user] && $_POST[pass]) {
if ($_POST[user]==$username && $_POST[pass]==$password) {
setcookie ("user", md5($_POST[user]), $time+3200);
setcookie ("pass", md5($_POST[pass]), $time+3200);
header("Location: http://www.cnn.com");
} else { $login_error= true;
echo "You are not authorized!";
}
}
}
else
{
?>

PHP

180

<form action="<?php echo $_SERVER['PHP_SELF']; ?>" method=post>


<table align=center style="font-family:arial; font-size:12; border:1 solid
#000000;">
<tr><td colspan=2 align=center bgcolor=#abcdef>LOGIN</td></tr>
<tr><td align=right>Username: </td><td><input type=text name=user
size=15></td></tr>
<tr><td align=right>Password: </td><td><input type=password name=pass
size=15></td></tr>
<tr><td align=center colspan=2><input type=submit value=Login></td></tr>
</table>
</form>
<?php
}
?>

2.

Test the program with a Apache server (XAMPP). First use a set of incorrect user name and password, and then
try with the correct ones.

3.

Capture a screen shot similar to the above figure and paste it to a Word document named lab11.doc (or
lab11.docx).

Submitting the lab


1. Create a .zip file named lab11.zip containing:
Lab11_1.php
Lab11_2.php
Lab11_3.php
Lab11_4.php
Lab11_5.php
Lab11.doc (or .docx and make sure this file contains all the five screen shots)
2.

Upload the zipped file as response to question 11 or Assignment 11 (available in Blackboard).

PHP

181

Lecture #12

PHP and MySQL

Concept of
data-driven
web site

With most of the services on the web being powered by web database applications, it becomes
important for any web developer to know how bring together the web and databases to build
applications, namely create a data-driven web site. By definition, a data-driven Web site is one in
which the content comes from some back-end data source, such as a database, and is then formatted
and presented to the user by the Web server. Typically, data-driven sites are dynamic; they present
information that is live rather than static. The benefits of using data-driven sites are numerous.
Implementing data-driven Web sites requires choosing and deploying the right infrastructure.
MySQL is the most popular open source database management system. PHP has a very good
support on MySQL. This framework uses the PHP scripting language and the MySQL relational
database. According to the http://www.php.net site, PHP and MySQL are the worlds best
combination for creating data-driven sites.

PHP +
MySQL

MySQL is an open source relational database management system (RDBMS) that uses Structured
Query Language (SQL). SQL is the language used in a query to request information from a
database. It is an easy-to-learn language. For example, to query a list of movies by Jackie Chan
could be generated with the following query:
SELECT title FROM movies WHERE actor = "jackie chan";

The SELECT statement is used to query the database and retrieve selected data that match the
field(s) you specify. The keyword FROM specifies the table that will be queried to retrieve the
desired results. The WHERE clause (optional) specifies which data values or rows will be returned or
displayed, based on the criteria described after it.
Suppose that your MySQL has a database named Entertainment, in which there is a table named
Movies. This Movies table has five fields: PartID, Title, Actor, Type, and Cost. There are two
records in the Movies table that match the criteria, so the above SQL statement will generate a
query result telling you there are two Jackie Chans movies, Rush Hour I and Rush Hour II, in
your database.
Table: Movies
PartID
.....
A1098
.....
A2017
.....

Title
.....
Rush Hour I
.....
Rush Hour II
.....

Actor
.....
Jackie Chan
.....
Jackie Chan
.....

Type
.....
DVD
.....
DVD
.....

Cost
.....
$10.95
.....
$14.95
.....

You can take a crash course to learn SQL at http://www.w3schools.com/SQL/default.asp.


The MySQL server is a DBMS (Database Management System) design to host databases and
provide general maintenance service to users, so you can create table, store data, query useful
records, and so on. You can download the latest version of MySQL at http://www.mysql.com/.
Documentation for MySQL can be found at http://dev.mysql.com/doc/. It also supports the
Microsoft Windows platform.
If you are using Linux (e.g. Red Hat Fedora Core 4 and later), PHP and MySQL are included in the
installation CDs.
Using PHPMySQL
functions to
PHP

In order to retrieve data from a database server through the Web, a client browser must gain access
to the database server (e.g. MySQL) and the database stored in that server, then use SQL statement
to provide query information to produce the query results.

182

access an
existing
MySQL
Database

PHP code, aimed at retrieving data from a remote database server, must be able to communicate
with the server through the Web, send request for authentication, specify the dataset to access, set
the criteria for the server to run the query, and eventually deliver the query results to the client
browser in HTML form.
PHP supports MySQL by providing functions specially designed for accessing, connecting, and
managing MySQL databases. See the table below for a list of MySQL functions.
Table 1: MySQL functions
mysql_connect
mysql_create_db
mysql_db_name
mysql_db_query
mysql_drop_db
mysql_error
mysql_fetch_array
mysql_fetch_assoc
mysql_fetch_field
mysql_fetch_lengths
mysql_fetch_object
mysql_fetch_row
mysql_field_flags
mysql_field_len
mysql_field_name
mysql_list_dbs
mysql_list_fields
mysql_list_processes
mysql_list_tables
mysql_num_fields
mysql_num_rows
mysql_pconnect
mysql_query
mysql_real_escape_string
mysql_result
mysql_select_db

Open a connection to a MySQL Server


Create a MySQL database
Get result data
Send a MySQL query
Drop (delete) a MySQL database
Returns the text of the error message from previous MySQL operation
Fetch a result row as an associative array, a numeric array, or both
Fetch a result row as an associative array
Get column information from a result and return as an object
Get the length of each output in a result
Fetch a result row as an object
Get a result row as an enumerated array
Get the flags associated with the specified field in a result
Returns the length of the specified field
Get the name of the specified field in a result
List databases available on a MySQL server
List MySQL table fields
List MySQL processes
List tables in a MySQL database
Get number of fields in result
Get number of rows in result
Open a persistent connection to a MySQL server
Send a MySQL query
Escapes special characters in a string for use in a SQL statement
Get result data
Select a MySQL database

When executed, the mysql_connect() function will attempt to establish a connection to the
database and return a resource representing that connection. If the attempt fails for any reason,
mysql_connect() will return a Boolean false. The syntax for mysql_connect() is:
mysql_connect(hostname, username, password)

The $hostname parameter is the address of the MySQL server to connect to using the username
and password provided by the $username and $password parameters. The address may include
the port to the server and the path. For example, a user cis246 with password t@sk93 attempts
to access a given host example.com that uses its port 3307 for MySQL. For example:
mysql_connect("example.com:3307", "cis246", "t@sk93")

In most of the cases, your PHP and the MySQL service are provided by the same server, the default
hostname is localhost.
$con = mysql_connect("localhost", "cis246", "t@sk93")

In PHP, assign a variable, e.g., $con, to represent the mysql_connect() function. This variable is
called a link identifier, or a database handle. With this identifier, you can later use the
PHP

183

mysql_close() function to close the built MySQL connection. For example:


mysql_close($con);

The die() or the exit() function outputs a message and terminate the current script.
<?php
$con = mysql_connect("localhost", "cis246", "t@sk93")
or die("Unable to connect to MySQL!");
mysql_close($con);
?>

The mysql_error() function returns the text of the error message from previous MySQL
operation. You can enclose it with either die() or exit() function. For example:
<?php
$con = mysql_connect("localhost", "cis246", "t@sk93")
or exit(mysql_error());
mysql_close($con);
?>

If the above PHP code fails to connect to the server, a default error message similar to the following
appears.
Access denied for user 'cis246'@'localhost' (using password: YES)

Some programmers prefer declaring variables with assigned values to handle the three parameters,
hostname, username, and password, of the mysql_connect() function. The main advantage is
that users can enter the values through an HTML form. For example:
<?php
$hostname = "localhost";
$username = "cis246";
$password = "t@sk93";
$con = mysql_connect($hostname, $username, $password)
or die("Unable to connect to MySQL!");
?>

The mysql_list_dbs() function lists databases available on a MySQL server. The


mysql_list_dbs() syntax is:
mysql_list_dbs(link_identifier)

To display details of each available database, use a while loop with a PHP function (e.g., print_r()),
as shown below:
<?php
$con = mysql_connect("localhost", "cis246","t@sk93")
or exit(mysql_error());
$dbs = mysql_list_dbs($con);
while ($row = mysql_fetch_object($dbs)) {
print_r($row);
}
mysql_close($con);
?>

A sample output looks similar to the following.


PHP

184

stdClass Object ( [Database] => information_schema ) stdClass


Object ( [Database] => students ) stdClass Object ( [Database]
=> ........)

The pair, [Database] => students, indicates that Database is the file name and student is
one piece of data in that field.
The above PHP code uses the mysql_fetch_object() function to return an object with
properties that correspond to the fetched row and moves the internal data pointer ahead. It fetches
data on a row-by-row basis. The while loop is commonly used to display data row by row. The
mysql_fecth_object() syntax is:
mysql_fetch_object(resource)

The mysql_fetch_object() function returns the current row as an object with member variables for
each column in the result set. For example, you can declare a variable $row to represent the object.
$row = mysql_fetch_object(result)
.......
$row->table_field_name

The following demonstrates how you can identify each data in a given row by using
$row->table_field_name. When using with a while loop, each subsequent call to
mysql_fetch_object() returns the next row in the recordset.
<?php
$con = mysql_connect("localhost", "cis246", "t@sk93")
or exit(mysql_error());
$dbs = mysql_list_dbs($con);
while ($row = mysql_fetch_object($dbs)) {
echo "<li>" . $row->Database;
}
mysql_close($con);
?>

A sample output looks like:

information_schema
students
courses

In the above example, resource is the $dbs variable which represents a list of database available in
the MySQL server.
The mysql_list_tables() function retrieves a list of table names from a MySQL database.
mysql_list_tables(database)

where database is the name of the database (e.g. students). Consider the following example. The
mysql_fetch_row() function fetches one row of data from the result associated with the

specified result identifier. The row is returned as an array. Each result column is stored in an array
offset, starting at offset 0.
<?php
$con = mysql_connect("localhost", "cis246", "t@sk93")

PHP

185

or exit(mysql_error());
$tb = mysql_list_tables(courses);
while ($row = mysql_fetch_row($tb)) {
print_r($row);
}
mysql_close($con);
?>

The mysql_select_db() function is used to declare the database from which to query. It sets the
current active database on the server that's associated with the specified link identifier. The
mysql_select_db() syntax is:
mysql_select_db(database, link);

where database is the name of the database to use, and the optional parameter link is the
database connection resource returned from the mysql_connect() function. For example, to
access a database students, use:
<?php
$con = mysql_connect("localhost", "cis246", "t@sk93")
or exit(mysql_error());
$db = mysql_select_db("students",$con)
or die(mysql_error());
mysql_close($con);
?>

or,
<?php
$con = mysql_connect("localhost", "cis246", "t@sk93")
or exit(mysql_error());
if (mysql_select_db("students")) { }
else {
die(mysql_error());
}
mysql_close($con);
?>

The link parameter is optional. In every case, PHP will use the last opened connection. If no
connection is open, it will attempt to open one automatically. It is strongly recommended that you
provide a link explicitly to avoid problems as your applications become more advanced.
Using PHP
function to
make a SQL
query

The mysql_query() function sends a single query to the currently active database on the server
thats associated with the specified link (identifier). After connecting to the correct MySQL
database, use the mysql_query() function to perform a query against the database from within PHP.
The mysql_query() syntax is:
mysql_query(query, link);

where query is a single SQL query to execute and the optional parameter link is the value
returned from mysql_connect(). As before, PHP will use the last opened connection if you do
not provide the link parameter. For example, to access a table named Assignments of the
students database, use:
<?php

PHP

186

$con = mysql_connect("localhost", "cis246", "t@sk93")


or exit(mysql_error());
$db = mysql_select_db("students",$con)
or die(mysql_error());
$sql = mysql_query("select * from Assignments");
while($row = mysql_fetch_array($sql)){
echo "<li>" . $row[0];
}
mysql_close($con);
?>

or,
<?php
$con = mysql_connect("localhost", "cis246", "t@sk93")
or exit(mysql_error());
if (mysql_select_db("students")) {
$sql = mysql_query("select * from Assignments");
while($row = mysql_fetch_array($sql)){
echo "<li>" . $row[0];
}
}
else {
die(mysql_error());
}
mysql_close($con);
?>

Upon successful execution, mysql_query() will return a resource representing the result set or a
Boolean false if the query failed. Note that a query is considered a success even if no results are
returned; mysql_query() will only fail if the query itself was malformed or otherwise unable to
execute on the server. Determining if any results were actually returned from a query requires a
different method.
The above example use the mysql_fetch_array() function. It returns a row from a recordset as
an associative array and/or a numeric array. This function gets a row from the mysql_query()
function and returns an array of success, or FALSE on failure or when there are no more rows. The
syntax for the mysql_fetch_array() function is:
mysql_fetch_array(result, result_type)

where result is the query result, which is represented by the $sql variable in the above code. This
result comes from a call to mysql_query(). Consider the following sample Assignment table. It
has three rows of records. Each record has 4 piece of data.
SID
D00991021
D 099102
D00991 23

$row[0]
row['SID']

PHP

First
Kristen
Spencer
Helen


Table: Assignments
Last
Campus
Steward
POM
Grammar
SHO
McBean
LB



$row[1]
$ ow[ First']

$row[2]
$row['Last']

187

$row[3]
$row['Campus']

row1
row2
row3

The mysql_fetch_array() function retrieves a row of record each time when the while loop
runs. For example:
("D00991021","Kristen","Steward","POM")

In the while loop, the $row variable is used in each loop to represent the array of data of that record.
There are two ways to identify each piece of data in that array: by index or by field name.
Each element of the array is given an index, starting with 0. Therefore:
$row[0]="D00991021"
$row[1]="Kristen"
$row[2]="Steward"
$row[3]="POM"

To display each piece of data in a given row, use:


while($row = mysql_fetch_array($sql)){
echo "<li>".$row[0].",".$row[1].",".$row[2].",".$row[3];
}

The output looks like:

D00991021,Kristen,Steward,POM
D00991022,Spencer,Grammar,SHO
D00991023,Helen,McBean,LB

Since the table has field names: SID, First, Last, and Campus. So, the following works as well:
$row['SID']="D00991021"
$row['First']="Kristen"
$row['Last']="Steward"
$row['Campus']="POM"

The above code can be rewritten to :


while($row = mysql_fetch_array($sql)){
echo "<li>" . $row['SID'] . "," . $row['First'] . "," .
$row['Last'] . "," . $row['Campus'];
}

The mysql_fetch_assoc() function works similarly to mysql_fetch_array() function the except


it returns an associative array of strings that corresponds to the fetched row. With this function the
name of each column must be the keys in the array. It does not support numeric indexes such as 0,
1, 2, etc. For example:
correct

incorrect

$row = mysql_fetch_assoc(result)
$row['column_name']

$row = mysql_fetch_assoc($result)
$row[n]

If two or more columns of the result have the same field names, the last column will take
precedence. You should avoid having such as table.
The mysql_fetch_object() function returns a row from a recordset as an object. It gets a row
from the mysql_query() function and returns an object on success. So, it is also a good candidate for
retrieving data with its link_identifier->FieldName format. Consider the following code,
which uses the print_r() function to return all records stored in the CIS110 table.
PHP

188

<?php
$con = mysql_connect("localhost", "cis246", "t@sk93")
or exit(mysql_error());
$db = mysql_select_db("students",$con)
or die(mysql_error());
$sql = mysql_query("select * from CIS110");
while($row = mysql_fetch_object($sql)) {
print_r($row);
}
mysql_close($con);
?>

If you have access to the MySQL server, a simple SELECT * FROM CIS110 statement can
return all the records stored in the CIS110 table with the MySQL format.
mysql> SELECT * FROM CIS110;
+-----------+----------+-----------+
| SID
| LastName | FirstName |
+-----------+----------+-----------+
| D99007374 | Chen
| Kristina |
| D99007375 | Okida
| Naomi
|
| D99007376 | Tran
| Victoria |
+-----------+----------+-----------+

The following code use <table>, <th>, <tr>, and <td> HTML tags to organize the outputs inside an
HTML table. It also illustrates how you retrieve data in the link_identifier->FieldName
format.
<?php
$con = mysql_connect("localhost", "cis246", "t@sk93")
or exit(mysql_error());
$db = mysql_select_db("students",$con)
or die(mysql_error());
$sql = mysql_query("select * from CIS110");
echo "<table cellspacing='0' border='1'>";
echo "<tr><th>SID</th><th>FirstName</th><th>LastName</th></tr>";
while($row = mysql_fetch_object($sql)) {
$sid = $row -> SID;
$LastName = $row -> LastName;
$firstName = $row -> FirstName;
echo("<tr><td>$sid</td><td>$LastName</td><td>$FirstName</td></tr>")
;
}
echo "</table>";
mysql_close($con);
?>

The mysql_fetch_row() function is another popular choice to return a numerical array that
corresponds to the fetched row and moves the internal data pointer ahead. The following example
uses the print_r() function to return detailed information about the array of each row.
<?php

PHP

189

$con = mysql_connect("localhost", "cis246", "t@sk93")


or exit(mysql_error());
$db = mysql_select_db("students",$con)
$sql = mysql_query("select * from CIS110");
print_r(mysql_fetch_row($sql));
mysql_close($con);
?>

A sample output of the above code looks like:


Array ([0] => D00991021 [1] => Kristen [2] => steward [3] => POM .....
)

The following code uses the mysql_fetch_row() function and its index-based format to organize
data in an HTML form.
<?php
$con = mysql_connect("localhost", "cis246", "t@sk93")
or exit(mysql_error());
$db = mysql_select_db("students",$con)
or die(mysql_error());
$sql = mysql_query("select * from CIS110");
echo "<table cellspacing='0' border='1'>";
echo "<tr><th>SID</th><th>FirstName</th><th>LastName</th></tr>";
while($row = mysql_fetch_row($sql)) {
echo("<tr><td>$row[0]</td><td>$row[1]</td><td>$row[2]</td></tr>");
}
echo "</table>";
mysql_close($con);
?>

The mysql_num_rows() function returns the number of rows in result. This command is only
valid for statements like SELECT or SHOW that return an actual result set. Similarly, the
mysql_num_fields() function returns the number of fields in result. For example:
<?php
$con = mysql_connect("localhost", "cis246", "t@sk93")
or exit(mysql_error());
$db = mysql_select_db("students",$con)
or die(mysql_error());
$sql = mysql_query("select * from Assignments");
echo "There are ". mysql_num_rows($sql) ." records, each has ".
mysql_num_fields($sql) ." field(s).";
mysql_close($con);
?>

Handling the
errors

Any time an error occurs when PHP is interacting with the database (except when you are
attempting to establish a connection to the database), you can use the mysql_error() and
mysql_errno() functions to handle them. Their syntaxes are:
mysql_error([$link]);

PHP

190

mysql_errno([$link]);

where the optional parameter $link represents the database connection for which to retrieve the last
error message. The mysql_error() provides a string error message and mysql_errno() returns the
actual integer error code.
These two functions report the error from the last MySQL function. But the mysql_error() function
only returns the error text from the most recently executed MySQL function.
To illustrate the use of these functions, consider the following small code snippet. Assume $link is
a valid database connection:
<?php
$con = mysql_connect("localhost", "cis246", "t@sk93")
or die(mysql_errno() . ": <br>" . mysql_error());
?>

Assuming that the above username does not exist, the following output will display to the browser:
1045:
Access denied for user 'cis246'@'localhost' (using password: YES)

You can suppress the error message on failure by prefixing a @ sign to the function name. For
example:
$con = @mysql_connect("localhost", "root", "mypasswd");

Implementin
g SQL
statement

In addition to using the PHP functions, you can create a PHP code template to send SQL statements
to the MySQL server. In the following example, the SQL statement select * from CIS110 is
what the PHP code sends to the MySQL server. You can try to replace it with another SQL
statement drop table CIS110 and delete the CIS110 table. Since the SQL statement is the
only part that changes, you can treat the following PHP code as a template.
<?php
$con = mysql_connect("localhost", "cis246", "t@sk93")
or exit(mysql_error());
$db = mysql_select_db("students",$con)
$sql = mysql_query("select * from CIS110");
mysql_close($con);
?>

Consider the following PHP code of learning activity #3, which creates a simple interface that can
send a SQL statement to the MySQL server. Consequently, you can manage your database through
the Web. The output looks like:

Some programmer express their concern about security. To authenticate the user, simply add a
userID and password verification function, as shown below, so only authorized users can use the
PHP

191

interface to manage the MySQL database.


<?php
if ($_POST)
{
$str=$_POST["mysql"];
$uid=$_POST["uid"];
$psd=$_POST["psd"];
if (($uid=="cis246") && ($psd=="t@sk93")) {//authentication
$con = mysql_connect("localhost","$uid","$psd") or die('Could not
connect: ' . mysql_error());
if(mysql_select_db("students"))
{
$query = mysql_query($str);
if ($query) {
echo "<p>Executed Successfully!</p><hr size=1 width='100%'>";
}
else {
echo "<p>Executed failed!</p>";
}
while($row=mysql_fetch_row($query)){
foreach ($row as $rs) {
echo $rs . ",";
}
echo "<br>";
}
mysql_close();
}
else
{
die( "Error! Could not connect the database: " . mysql_error() );
}
}
else { echo "Invalid username or password!";
}
}
else
{
?>
<html>
<body>
<form action="<?php echo $_SERVER['PHP_SELF'];?>" method="post">
User ID: <input type="text" name="uid"><br>
Password: <input type="password" name="psd">
<p>SQL Statement:<br>
<textarea rows=10 cols=100 name="mysql"></textarea><br>
<input type="submit" value="Submit">
</form>
</body>

PHP

192

</html>
<?php
}
?>

The interface now looks:

Input data
through
HTML forms

The following is the code that creates a simple HTML form. The method property of the <form>
tag is set to be post; therefore, the user input may be retreieved through Internet with
$FirstName = $_POST["FirstName"], $LastName = $_POST["LastName"], $Email =
$_POST["Email"], and $StudentID = $_POST["StudentID"] respectively, after the user submits
them.
<form action="<?php echo $_SERVER['PHP_SELF'];?>" method="post">
First Name: <input type="text" name="FirstName"><br>
Last Name: <input type="text" name="LastName"><br>
Email: <input type="text" name="Email"><br>
Student ID: <input type="text" name="StudentID"><br>
<input type="submit" value="Submit">
</form>

You can write an PHP code using this concept. First, retrieved the user input in a data-by-data
manner.
<?php
if ($_POST)
{
$FirstName = $_POST["FirstName"];
$LastName = $_POST["LastName"];
$Email = $_POST["Email"];
$StudentID = $_POST["StudentID"];

Secondly, access the database.


$con = mysql_connect("localhost","root","");
if(mysql_select_db("games"))
{

Thirdly, use INSERT INTO statement to add these data to the table.
$sql = "INSERT INTO contacts VALUES ('$FirstName', '$LastName',
'$Email', '$StudentID')";
$query = mysql_query($sql);

PHP

193

Finally, you can retrieved data using a proper SQL statement from the table to see the result. For
example,
SELECT * FROM contacts WHERE $FirstName = 'Jennifer';

Review
Questions

1. Given the following code segment, which statement is correct?


$conn = mysql_connect("localhost","joeuser","34Nhjp") or
die(mysql_error());

A. The die() function would execute only if the connection failed.


B. The mysql_error() function prints an error message when connect to the database.
C. The database name is localhost, your username is 34Nhjp, and your password is joeuser.
D. The mysql_connect() function selects a database on the MySQL server.
2. Given the following code segment, which statement is correct?
$db = mysql_select_db("MyDB", $conn);

A. It selects a MySQL database called MyDB.


B. It selects a table called MyDB.
C. It selects a column called MyDB.
D. It selects a record called MyDB.
3. Given the following code segment, which statement is correct?
$result = mysql_query($sql,$conn);

A. $result formats the results held by the mysql_query() function.


B. $result is a variable to hold the result of the query, carried out by the mysql_query() function.
C. $result is built-in function that access the data delivered by mysql_query() function.
D. $result is built-in function that carries out the query held by mysql_query() function.
4. Given the following PHP code segment, which is the part that builds a connection to MySQL
server named "cis246" using the "admin" account with password "solo123"?
A. $conn = mysql_select_db("cis246","admin","solo123");
B. $conn = mysql_connect("cis246","admin","solo123");
C. $conn = mysql_query("cis246","admin","solo123");
D. $conn = mysql_db_connection("cis246","admin","solo123");
5. The __ function selects a database on the MySQL server for use by subsequent queries.
A. mysql_connect()
B. mysql_query()
C. mysql_select_db()
D. mysql_fetch_array()
6. Which PHP-MySQL function will return meaningful error message when something goes wrong
with the connection or query?
A. mysql_php_error()
B. query_error()
C. mysql_query_error()
D. mysql_error()
7. Given the following code segment, what does the "@" sign do?
$con = @mysql_connect("localhost", "root", "mypasswd");

PHP

194

A. It is a default variable that holds the result of the mysql_query() function.


B. It suppress warnings, as well as the die() function to cause the code to end and a message to be
displayed if the query fails.
C. It forces the database to release data even if the username and password is incorrect.
D. It means "at the time the database is connected, check the username and password".
8. Given the following code segment, __.
$con = @mysql_connect("localhost", "root", "mypasswd");
if (!$con) {
echo( "Unable to connect to the " .
"database server at this time." );
exit();
}

A. placing a @ symbol in front of the function name tells the function not to automatically display
error messages when they fail.
B. when the username/password combination is not accepted by the server, the if(!$con) statement
will take effect.
C. the value returned by mysql_connect is stored in a variable named $con.
D. All of the above.
9. Given the following code segment, __.
$result = mysql_query("SELECT * FROM student");
while ( $row = mysql_fetch_array($result) ) {
echo{$row["firstName"]);
}

A. "student" is the name of the database.


B. $row is a row in the result set, then $row["firstName"] is the value in the firstName column of
that row.
C. the while loop will stop when $row["firstName"] equals "student".
D. None of the above.
10. Once you have a database connection, the next step is to use __ function to select the database
that you will be performing queries against.
A. mysql_select_db()
B. mysql_query()
C. mysql_fetch()
D. mysql_connect()

PHP

195

Lab #12

PHP and MySQL

Preparation #1:
1. Start both Apache and MySQL services.
2. Click the Admin button next to MySQL.

3.

Wait till the phpMyAdmin console opens. You will need to use http://localhost:81/phpadmin if you
changed the port setting.

4.

Click the Database tab. Create a new database named games as shown below.

5.

In the left pane, make sure the games database is added to the list.

Preparation #2: Create a PHP-base SQL Console


1. In the X:\xampp\htdocs\myphp directory, use Notepad to create a new text file named sql.php with the
following contents:

PHP

196

<?php
if ($_POST)
{
$str=$_POST["mysql"];
$uid=$_POST["uid"];
$psd=$_POST["psd"];
if (($uid=="cis246") && ($psd=="student")) { // you can set your own values
$con = mysql_connect("localhost","root",""); // do not modify this line
if(mysql_select_db("games"))
{
$query = mysql_query($str);
if ($query) {
echo "<p>Executed Successfully!</p><hr size=1 width='100%'>";
}
else {
echo "<p>Executed failed!". mysql_error() ."</p>";
}
while($row=mysql_fetch_row($query)){
foreach ($row as $rs) {
echo $rs . ",";
}
echo "<br>";
}
mysql_close();
}
else
{
die( "Error! Could not connect the database: " . mysql_error() );
}
}
else { echo "Invalid username or password!";
}
}
else
{
?>
<html>
<body>
<form action="<?php echo $_SERVER['PHP_SELF'];?>" method="post">
User ID: <input type="text" name="uid"><br>
Password: <input type="password" name="psd">
<p>SQL Statememt:<br>
<textarea rows=10 cols=100 name="mysql"></textarea><br>
<input type="submit" value="Submit">
</form>
</body>
</html>

PHP

197

<?php
}
?>

2.
3.

Start both Apache and MySql services. Make sure they are up and running.
Open a browser window and visit http://localhost/myphp/sql.php (or http://localhost:81/myphp/sql.php), you
should see the following window.

4.

To test if your sql.php code can communicate with the MySql server, enter the User ID and password you set to
the sql.php file, enter the following SQL statement, and then click Submit.
show databases;

5.

The expected output is similar to the following. Make sure the games database is included. Go back to
preparation #1 if it is not included.

Learning Activity #1: Creating a table using embedded SQL statement


1. Use Notepad to create a new PHP script file named lab12_1.php with the following contents:
<?php
// connect to the server
$con = mysql_connect("localhost","root","") or die("Error! Could not connect to
server: " . mysql_error());
echo "Connected to Server.<br>\n";
// select the database
$db = mysql_select_db('games')
or die("Error! Could not access the database: " . mysql_error());
echo "Accessed the database.<br>";

PHP

198

// SQL statement to create the contact table


$sql= "CREATE TABLE contacts (
lastName VARCHAR(20),
firstName VARCHAR(20),
email VARCHAR(50),
id VARCHAR(9),
UNIQUE (id) )";
if(mysql_query($sql)) {
echo "Table created successfully.<br>";
}
else {
die("Error! Could not create table: " . mysql_error());
}
// Insert sample data
$sql = "INSERT INTO contacts VALUES
('Jon' , 'Doe', 'jdoe@server.com', 'D00991301') ,
('Suzie' , 'Cue', 'scue@server.com', 'D00991302'),
('Joe', 'Somebody', 'jsom@server.com', 'D00991303')";
if(mysql_query($sql)) {
echo "Values inserted successfully.";
}
else {
die("Error! Could not insert values: " . mysql_error());
}
mysql_close($con);
?>

2.

Access the lab12_1.php file. You should see the following output if theres no typos or errors. Notice that you
can only create the contact table ONCE.

3.

Capture a screen shot similar to the above figure and paste it to a Word document named lab12.doc (or
lab12.docx).

Learning Activity #2: Accessing a given table from MySQL using PHP
1. Use Notepad to create a new file named lab12_2.php with the following contents:
<?php
$con = mysql_connect('localhost', 'root', '')
or die("Error! Could not connect to server: " . mysql_error());
echo "Connected to Server.<br>\n";
$db = mysql_select_db('games')
or die("Error! Could not access the database: " . mysql_error());
echo "Accessed the database.<br>";
$sql = mysql_query("SELECT * FROM contacts ORDER BY LastName, FirstName");

PHP

199

if($sql) {
while($row = mysql_fetch_object($sql)) { // method 1
$id = $row -> id;
$lastName = $row -> lastName;
$firstName = $row -> firstName;
echo("$id, $lastName, $firstName<br>");
}
}
else {
exit( "Cannot access database: " . mysql_error() );
}
echo "<hr size='1' width='100%'>";
$sql = mysql_query("SELECT * FROM contacts ORDER BY LastName, FirstName");
while ($row = mysql_fetch_array($sql)) { // method 2
echo $row['id'] . ", " . $row['firstName'] . ", " . $row['lastName'] . "<br>";
}
echo "<hr size='1' width='100%'>";
echo "<table border='1' cellspacing='0'>";
echo
"<tr><th>FirstName</th><th>LastName</th><th>Email</th><th>StudentID</th></tr>";
$sql = mysql_query("SELECT * FROM contacts ORDER BY LastName, FirstName");
while ($row = mysql_fetch_row($sql)) { // method 3
echo "<tr><td>$row[0]</td><td>$row[1]</td><td>$row[2]</td><td>$row[3]</td></tr>";
}
echo "</table>";
mysql_close($con);
?>

2.

Access the lab12_2.php file. You should see the following output, if theres no typos or errors.

3.

Capture a screen shot similar to the above figure and paste it to a Word document named lab12.doc (or
lab12.docx).

Learning Activity #3: Interface to insert new data


1. Use Notepad to create a new file named lab12_3.php with the following contents:
<?php
if ($_POST)
{
$uid=$_POST["uid"];
$psd=$_POST["psd"];

PHP

200

if (($uid=="cis246") && ($psd=="student")) { // you can set your own values


$FirstName = $_POST["FirstName"];
$LastName = $_POST["LastName"];
$Email = $_POST["Email"];
$StudentID = $_POST["StudentID"];
$con = mysql_connect("localhost","root",""); // do not modify this line
if(mysql_select_db("games"))
{
$sql = "INSERT INTO contacts VALUES ('$FirstName', '$LastName', '$Email',
'$StudentID')";
$query = mysql_query($sql);
if ($query) {
echo "<p>Executed Successfully!</p><hr size=1 width='100%'>";
}
else {
echo "<p>Executed failed!". mysql_error() ."</p>";
}
echo "<table border='1' cellspacing='0'>";
echo
"<tr><th>FirstName</th><th>LastName</th><th>Email</th><th>StudentID</th></tr>";
$sql = mysql_query("SELECT * FROM contacts ORDER BY LastName, FirstName");
while ($row = mysql_fetch_row($sql)) { // method 3
echo
"<tr><td>$row[0]</td><td>$row[1]</td><td>$row[2]</td><td>$row[3]</td></tr>";
}
echo "</table>";
mysql_close();
}
else
{
die( "Error! Could not connect the database: " . mysql_error() );
}
}
else { echo "Invalid username or password!";
}
}
else
{
?>
<html>
<body>
<form action="<?php echo $_SERVER['PHP_SELF'];?>" method="post">
User ID: <input type="text" name="uid"><br>
Password: <input type="password" name="psd">
<hr size=1 width=100%>
First Name: <input type="text" name="FirstName"><br>
Last Name: <input type="text" name="LastName"><br>
Email: <input type="text" name="Email"><br>
Student ID: <input type="text" name="StudentID"><br>

PHP

201

<input type="submit" value="Submit">


</form>
</body>
</html>
<?php
}
?>
2.

Access the lab12_3.php file. You should see the following output, if theres no typos or errors. Add your
information to the database.

to
3.

Capture a screen shot similar to the above figure and paste it to a Word document named lab12.doc (or
lab12.docx).

Learning Activity #4:


1. Use the sql.php to process the following SQL statements to create a new table for lab12_4.php.
CREATE TABLE requests (
Name VARCHAR(40),
Address VARCHAR(150),
Edu_level VARCHAR(20),
Attend_method VARCHAR(20),
id INT AUTO_INCREMENT,
UNIQUE (id)
);

2.

Use Notepad to create a new file named lab12_4.php with the following contents:
<?php
if ($_POST)
{
$con = mysql_connect( 'localhost', 'root', '' )
or die("Error! Could not connect to database: " . mysql_error());
$db = mysql_select_db('games')
or die( "Error! Could not select the database: " . mysql_error());
$name = $_POST['name'];
$address = $_POST['address'];
$edu = $_POST['edu_level'];
$atd = $_POST['attend_method'];
$sql = "INSERT INTO requests
(Name, Address, Edu_level, Attend_method)
VALUES
('$name' , '$address', '$edu', '$atd')";

PHP

202

mysql_query($sql) or die(mysql_error());
echo "Data submitted successfully.";
$sql = mysql_query("SELECT * FROM requests");
if($sql) {
echo "<table border=1 cellspacing=0 width=100%>";
echo "<tr><td>Name</td>
<td>Adress</td>
<td>Edu Level</td>
<td>Attend Method</td>
<td>ID</td></tr>";
while($row = mysql_fetch_array($sql)) {
echo "<tr><td>" . $row['Name'] .
"</td><td>" . $row['Address'] .
"</td><td>" . $row['Edu_level'] .
"</td><td>" . $row['Attend_method'] .
"</td><td>" . $row['id'] .
"</td></tr>";
}
echo "</table>";
}
else
{
die("Cannot access database: " . mysql_error());
}
mysql_close($con);
}
else
{
?>
<html>
<body>
<h4>Request Information</h4>
<form action="<?php echo $_SERVER['PHP_SELF'];?>" method="post">
Name: <input type="text" name="name" size=40><br>
Address: <input type="text" name="address" size=90><br>
<p>Highest
<br><input
<br><input
<br><input

education level completed?


type=radio name="edu_level" value="High school">High school
type=radio name="edu_level" value="College">College
type=radio name="edu_level" value="Graduate school">Graduate school

<p>How would you like to attend this class?


<select name="attend_method">
<option value="on_campus">On campus
<option value="online">Online
</select>
<p><input type="submit" value="Submit">
</form>
</body>
</html>
<?php
}
?>

PHP

203

3.
4.

Upload both files to your Tripod site using WebFTP or FrontPage.


Execute the lab12_4.php file by entering some records.

5.

Click the Submit button.

6.

Capture a screen shot similar to the above figure and paste it to a Word document named lab12.doc (or
lab12.docx).

Learning Activity #5: Creating a Blog site using PHP and MySQL
1. Use the sql.php to process the following SQL statements to create a new table for lab12_5.php.
CREATE TABLE Messages (
ID INT NOT NULL AUTO_INCREMENT PRIMARY KEY,
Message TEXT,
MsgDate DATE NOT NULL
);

2.

Create a new file named lab12_5.php with the following contents:


<?php
$addMsg=$_GET["addMsg"];
if (isset($addMsg)) // If the user wants to add a Message
{
?>
<form action="<?php echo $_SERVER['PHP_SELF'];?>" method="post">
<p>Post your Message:<br />
<textarea name="msg" rows="10" cols="70" wrap></textarea><br />
<input type="submit" name="smtmsg" value="SUBMIT" /></p>
</form>
<?php
}
else
{
if ($_POST)
{
$msg=$_POST["msg"];
$curDate = date("F j, Y, g:i a");
$con = mysql_connect('localhost', 'root', '') or die(mysql_error());

PHP

204

$db = mysql_select_db('games') or die(mysql_error());


$sql = "INSERT INTO Messages SET
Message='$msg',
MsgDate=CURDATE()";
mysql_query($sql) or die(mysql_error());
$sql = @mysql_query("select * from Messages ORDER BY MsgDate, id desc");
mysql_close($con);
$url = $_SERVER['PHP_SELF'];
header('Location: '.$url) ;
}
else
{
$url = $_SERVER['PHP_SELF'] ."?addMsg=1";
echo "<a href='$url'>Add message</a><hr size=1 width=100%>";
$con = mysql_connect("localhost", "roo","") or die(mysql_error());
$db = mysql_select_db("students")
or die(mysql_error());
$sql = @mysql_query("select * from Messages ORDER BY MsgDate, id desc");
echo "<table width='100%'>";
while($row = mysql_fetch_array($sql)){
echo "<tr><td width='120'>" . $row['MsgDate'] . "</td><td>";
echo $row['Message'] . "</td></tr>";
}
echo "</table>";
mysql_close($con);
}
}
?>

3.

Test the program with a Apache server (XAMPP). A sample output looks like:

4.

Click the Add message hyperlink and add few messages.

PHP

205

5.

Capture a screen shot similar to the above figure and paste it to a Word document named lab12.doc (or
lab12.docx).

Submitting the lab


1. Create a .zip file named lab12.zip containing:
Lab12_1.php
Lab12_2.php
Lab12_3.php
Lab12_4.php
Lab12_5.php
Lab12.doc (or .docx and make sure this file contains all the five screen shots)
2.

Upload the zipped file as response to question 11 or Assignment 12 (available in Blackboard).

PHP

206

Lecture #13

PHP Objects and classes

What is
Object
Orientation?

Object orientation is the logical grouping of common properties and functionalities into a new
class, and then attach the entire class to an object. For example, according the biology textbook,
the term "insect" is defined by grouping all the common properties (also known as attributes) and
functionalities (also known as methods):
"an animal that breathes air, has three pairs of legs and is
covered by a hard exoskeleton. It also has antennae, compound
eyes, and three main body parts."

Now, simply by declaring a beetle is an insect!, then you can immediately figure out that a beetle
breathes air, has three pairs of legs and is covered by a hard
exoskeleton. It also has antennae, compound eyes, and three main
body parts.
You figured that out simply because all the grouped properties and methods of the insect class
are applied to the beetle object after the object declaration. You can declare as many object as
you wish. After all, the Insect Class includes bees, ants, beetles, butterflies, moths, flies, crickets,
fleas, and many others.
A car, as an object, has many properties. It has make, model, year, color, etc. Each property, when
being assigned a valid value, will determine what this object is. For example, there are three cars in
a car dealer's parking lot. To identify each car, you assign an identification to each of them: car1,
car2, and car3. Given the following properties and their associated values, you immediately know
what those cars are.
car1

car2

car3

make="Lexus";
model="ES330";
length="191.1 in";
weight="3,472 lb";
cylinder="3.3-liter
V6";
color="silver";

make="Lexus";
model="ES330";
length="191.1 in";
weight="3,472 lb";
cylinder="3.3-liter
V6";
color="grey";

make="Lexus";
model="ES330";
length="191.1 in";
weight="3,472 lb";
cylinder="3.3-liter
V6";
color="white";

All the three cars have the following common attributes, except the color.
make
model
length
weight
cylinder
Simply create a class called "Lexus_ES330" with all the common attributes:
class Lexus_ES330() {
var $make="Lexus";
var $model="ES330";
var $length="191.1 in";
var $weight="3,472 lb";
var $cylinder="3.3-liter V6";
}

We can get a quick specification of the three cars, except for the color. Consequently, when you
hear someone says "Helen's car is a Lexus ES330", "Jack drives a Lexus ES330", and "Ann owns a
Lexus ES330", you can picture what kind of car Helen's, Jack's, and Ann's are.
PHP

207

On the other hand, a car has many built-in functions. A car must be able to start, stop, run,
accelerate, and stop. These functions must come with the car, otherwise, the car is not a functional
car. The "Lexus_ESS330" class will include all the necessary functions (officially known as
methods).
class Lexus_ES330 {
public $make="Lexus";
public $model="ES330";
public $length="191.1 in";
public $weight="3,472 lb";
public $cylinder="3.3-liter V6";
start() {
start the engine and keep it running;
}
accelerate() {
increase the spinning speed of engine;
}
...............
}

With a simply declaration like the following, a object called car4 will have all the common
properties and common functions a Lexus ES330 must have.
$car4 = new Lexus_ES330;

In order to mass produce cars, the car manufacturers use modularization technology to pre-produce
semi-finished components, and then assemble the components into a finished product in a
assembly line. A modularized components may apply to many model of cars. For example, Lexus
ES and LS use exactly the same radiator. In other words, a modularized radiator applies to ES and
LS. Similarly, a method may be used by many objects. For example, the "print()" method can be
used in a clickable button, a mouse-trigger menu, and/or a hyperlink.
Object orientation, in essence, is the grouping of common properties and methods into a class, and
later use the class as a template for associated objects. However, before you can create an object,
you must create a class. Consequently, creating a class to include common things for objects to
inherit is what object orientation is all about.
In a defined class, properties and methods all this class has is known as members of the class.
What is a
ObjectOriented
Programming?

The concept of object-oriented programming is built on the idea of treating a program as a finished
product of many individual components or objects. Each object one or more properties (or
attributes) and one or more functions (or methods).
Additionally, objects with common attributes form a class. Cars, bus, trains, and subway, etc. form
the transportation class. In Object Oriented programs, an object is a single instance in a class of
similar objects that share common properties. For example, an apple and an orange both are
objects of the "fruit" class, but are obviously distinct from each other.

Is PHP an
ObjectOriented
Language?

According to PHP manual, it is NOT an object-oriented language, but the version 5 of PHP
supports the object oriented programming model. PHP 5 now provides a new Object Model, which
uses the class keyword for users to define a class and create objects with common attributes.
In PHP, a related set of code, which is a sequence of instructions, can be organized into a function,
along with valid data units to form a structure. Data units are most likely to be variables. The
combination of functions and variables in the structure, form a PHP class.

PHP

208

Defining a class
A class is a collection of user-declared variables and user-defined functions with a well-designed
structure. In PHP, class definition begins with the keyword class, followed by a class name, which
can be any name that isn't a reserved word in PHP. Followed by a pair of curly braces, of which
contains the definition of the classes members and methods.
At its simplest, a class consists of the keyword class, a name, and a code block:
class ClassName {
PHP Codes
}

The class name can contain any combination of letters and numbers, as well as the underscore
character, but cannot begin with a number. Notice that instantiating an object is similar to calling a
function, and this confuses many new learners. As with a function call, you must supply
parentheses. Like functions, some classes require that you pass them arguments.
Defining class members: properties and methods
In the example below, a class named fruit is defined. This fruit class contains a user-declared
variable $str and a user defined function show(). Both $str and show() are members of the fruit
class. $str is the property of the class, while show() is the method of the class.
<?php
class fruit
{
var $str = "It is a fruit.";
function show()
{
echo $this -> str;
}
}
?>

Let's separate this fruit class into two sections to understand the class property and class method
definition.
Properties
Within the body of a class, you can declare special variables called properties. In the following
example, you declare a property and assign its value at the same time. You can get a quick peek at
the state of an object with the print_r() function.
<?php
class fruit
{
var $str = "It is a fruit.";
}
?>

The var keyword declare the $str variable as a string. Since PHP 5, var is not recommended,
because class variables (properties) are declared public, private, or protected to make PHP objectoriented. We will discuss this in the later section.
Methods
Class methods are functions declared within a class. In the following example, the show() method
is declared just as any function would be declared, except that is done within a class.
<?php

PHP

209

class fruit
{
............
function show()
{
echo strtoupper($this -> str);
}
}
?>

In the show() function, a pseudo-variable, $this, represent a future object that will use the class
(this object is not yet created). Notice that the fruit class is defined for a set of objects that share
the common structure and common behavior defined in this class. Outside of an object, there is a
handle you can use to access its elements. Inside an object, there is no such handle, so you must
fall back on $this.
The strtoupper() function will convert every letter to upper cases; the echo construct will display
the values on screen whenever the show() function is called.
Note the following syntax:
$this -> str

which is used to associate an object with the $str variable. In PHP, the member method or variable
is accessed using the -> operator, as shown in the last line.
Using class
members

The above demo code does not produce any output, simply because the entire class is not yet used
by any object. A class definition tells the computer what that class is; it defines properties and
methods. Before we can use the properties and methods, we must create an object (also known as
instance). This object needs to associate with the class to use the properties and methods. The
syntax is:
$objectName = new className();

You must use the new keyword. This tells the PHP engine that you wish to instantiate a new
object. The returned object can then be stored in a variable for later use.
By adding the following bold-faced lines, the $apple object immediately has all properties as
defined by the fruit class.
<?php
class fruit
{
var $str = "It is a fruit.";
function show()
{
echo strtoupper($this -> str);
}
}
$apple = new fruit();
echo $apple -> str;
?>

Consequently, the output is


It is a fruit.

On the other hands, the $apple object can use the show() function by associating the object name
PHP

210

with the function name using the -> operator.


<?php $apple->show(); ?>

The strtoupper() in the show() function will convert the string to upper cases, and the output will
be:
IT IS A FRUIT.

Creating
constructs to
use class
members

In object-oriented programming, a construct is a member function in a class that is automatically


called when you create a new instance of a class. It is a subprogram which constructs a value of a
private type from its component parts. Consider the following two examples, it compares a method
with a constructor.
Constructor

Method

<?php class fruit


{ var $str = "It is a fruit.";
function __construct() {
echo strtoupper($this -> str); }
}

<?php class fruit


{ var $str = "It is a fruit.";
function show() {
echo strtoupper($this -> str); }
}

$apple = new fruit();


?>

$apple = new fruit();


echo $apple -> str;
?>

The output is:


IT IS A FRUIT.

The output is:


IT IS A FRUIT.

As you can see, we can use __construct() to declare a PHP constructor for the fruit class. We then
create the $apple object and use it to call this constructor with the new keyword. Using the
constructor, we can bypass the need to use -> operator, which requires you to associate the object
with the class member.
In most of object-oriented languages, constructors have the same name as their class; therefore,
PHP 4 lets you create a constructor by declaring a method with the same name as that of the class.
In PHP 5, however, you are recommended to declare a constructor using __construct(). Be careful
the way of wring the __construct(), it has two (2) underscore signs in it. For example,
Constructor

Method

<?php class fruit


{
var $str = "It is a fruit.";
function fruit() {
echo strtoupper($this -> str); }
}

<?php class fruit


{
var $str = "It is a fruit.";
function show() {
echo strtoupper($this -> str); }
}

$apple = new fruit();


?>

$apple = new fruit();


echo $apple -> str;
?>

The output is:


IT IS A FRUIT.

The output is:


IT IS A FRUIT.

For backwards compatibility, if PHP 5 cannot find a __construct() function for a given class, it will
search for the old-style constructor function, by the name of the class. Effectively, this means that
the only case that would have compatibility issues is if the class had a method named __construct()
which was used for different semantics.

PHP

211

Advantages of
Using Classes
and Objects in
PHP

When building PHP applications, you often need to decide whether or not to make a property or a
method accessible. For example, if you are building a Sales class, you do not want to allow users
using the Sales class to access properties or methods that will change a user's ID. You can limit
access to properties and methods within the class (or sub-classes of the class) by setting the
properties and methods to private.
Although PHP was NOT designed as an object-oriented language, it is actually moving toward
being one. The true advantage is the use of visibility to control access to certain codes. Objectoriented programming is largely about the ability to hide what's not important to the user and to
highlight what is. One of the primary means for doing so is through defining scope for class
members.
Like other object-oriented languages, PHP use the following keywords to set the scope of class
members.
The public keyword specifies that a variable or function is available to any caller. Notice that
variables and functions are public by default.
The private keyword specifies that a variable or function is available only to the class that
declares or defines it, or to subclasses of that class. Private members are accessible within the
class in which they are created. Note that they are not accessible by any subclass!
The protected keyword limits access to inherited classes and to the class that defines the item.
Protected members are accessible within the class in which they are created, as well as by any
subclass.

Property
Visibility

Object orientated languages offer public, private, and protected member variables for developers
to determine the visibility of object properties. The various types of member variables are defined
as:
public variables - can be accessed as a property by any object that is associated with the class
the variable is in.
private variables - can only be accessed by functions (also known as methods) inside the same
class as object is associated with.
protected members - are like private variables, but they cannot be accessed from outside the
object.
In the following example, there are two individual classes--demo1 and demo2. Within the demo1
class, the keywords public, private and protected are used to declare three types of string
variables--public, private and protected member variables. Notice that the string variables are
declared inside the demo1 class only.
<?php
class demo1 {
private $prv = "My private data!<br>";
protected $prd = "My protected data!<br>";
public $pub = "My public data!<br>";
function show() {
echo $this->prv;
echo $this->prd;
echo $this->pub;
}
}
class demo2 extends demo1 {
function show() {
echo $this->prv;
echo $this->prd;
echo $this->pub;
}

PHP

212

}
// output of demo1()
$obj1 = new demo1();
$obj1->show();
echo "<hr>";
// output of demo2()
$obj2 = new demo2();
$obj2->show();
echo "<hr>";
// illustrate how protected members work
echo $obj2->prd;
?>

The output looks:


My private data!
My protected data!
My public data!
My protected data!
My public data!

Some error messages (e.g. Undefined property: demo2::$prv in ...)


Notice that the "My private data!" sentence is only displayed once! It's missing from the second
occurrence. This the result of being a private variable, which can only be accessed by functions
inside the demo1 class. The $prv variable is a member of demo1 and is hidden to demo2 class, plus
it is not declared in demo2.
In the above code, the "echo $obj2->prd" line demonstrates how the $prd member is actually
protected, and the following error is displayed:
Fatal error: Cannot access protected property demo2::$prd
in ..........

Method
Visibility

In PHP, methods can be marked public, private, and protected.


Private methods: Private methods are only accessible within the class in which they are
declared. Attempts to access private methods from outside of the originating class will simply
result in no action, rather than any error message.
Protected methods: Like protected members, protected methods are accessible both within the
class in which they are declared, as well as by all subclasses.
In the following example, the greeting1 class has one public variable $str, a private function
upcase() that converts every letter to upper case, and a public function show() that get results from
the upcase() function and returns the value of $str variable.
The greeting2() class has a function show() that attempts to access the private method (the
upcase() function) and return the value. Since a private method can be called only from within the
class. The "echo $obj2->show()" statement will cause an error.
<?php

PHP

213

class greeting1 {
public $str="How are you?<br>";
private function upcase(){
$this->str = strtoupper($this->str);
}
public function show(){
$this->upcase();
return $this->str;
}
}
class greeting2 extends greeting1 {
function show(){
$this->upcase();
return $this->str;
}
}
$obj1 = new greeting1();
echo $obj1->show();
$obj2 = new greeting2();
echo $obj2->show();
?>

The output looks like:


HOW ARE YOU?
PHP Fatal error: Call to private method greeting1::upcase() from
context 'greeting2' in ............

Accessing a
class members
via the class
(without
object)

The methods and properties you have seen so far all operate in object context. That is, you must
access them using an object instance, via the $this pseudo-variable or an object reference stored in
a standard variable. In some cases, you may find that it's more useful to access properties and
methods via a class rather than an object instance. Class members of this kind are known as static.
Using static property
Members of a class can also be marked "static". Declaring class members or methods as static
makes them accessible without needing an instantiation of the class. A member declared as static
cannot be accessed with an instantiated class object (though a static method can). A static member
is one that can be accessed directly through the class structure.
To declare a static property, place the keyword static after the visibility modifier, directly in front
of the property variable. For example:
<?php
class cis246 {
public static $title = "Learn PHP Programming!";
}
echo cis246::$title . "<br>";
?>

You can access a static property using the scope resolution operator, or the double colon (::). The
scope resolution operator should sit between the class name and the static property you wish to
access. The syntax is:
className::$variableName

PHP

214

As you can see, there is no need to instantiate an object to access the $title property. The output is
thus,
Learn PHP Programming!

Because static methods are callable without an instance of the object created, the pseudo variable
$this is not available inside the method declared as static. Notice that we're able to access the
variable $title before we have instantiated the class as an object. As a matter of fact, static
properties cannot be accessed through the object using the arrow operator ->.
The syntax for declaring and accessing static methods is similar. Once again, you should place the
static keyword after the visibility modifier. For example:
<?php
class cis246 {
public static $title = "Learn PHP Programming!";
public static function show() {
return strtoupper(self::$title);
}
}
echo cis246::show();
?>

Notice that the show() method refer to the $title property using the keyword self and the scope
resolution operator (::). You cannot use $this in a static method because $this is a reference to the
current object instance, but a static method is called via the class and not an object.
To call a static method from outside of its class, use the class name together with the scope
resolution operator and the name of the method, as shown in the line below:
echo cis246::show();

The output looks like:


LEARN PHP PROGRAMMING!

There are two good reasons why you might want to use a static method.
A utility operation may not require an object instance to do its job. By declaring it static, you
save client code the overhead of creating an object.
A static method is globally available. This means that you can set a value that all object
instances can access, and it makes static methods a great way of sharing key data across a
system.
Using class constants
While static properties are often declared private to prevent meddling, there is one way of creating
a read-only statically scoped property: You can declare a constant. Like its global cousin, a class
constant is immutable once defined. It is useful for status flags and for other things that don't
change during the life of a process, like the value of pi.
When programming a large application, it is useful to define constants on a per-class basis. A
constant's value remains the same and unchangeable as long as the class it resides is up and
running. You declare a class constant with the const keyword. For example, 6.022169 x 1023 is the
so-called Avogadro constant.
<?php
class atom {
const Avogadro = 6.022169e+23;

PHP

215

}
echo atom::Avogadro;
?>

Constants differ from normal variables in that you don't use the $ symbol to declare or use them.
Like static members, constant values cannot be accessed from an instance of the object (using
$object::constant). The output of the above code is:
6.022169E+23

Notice that class constants are always public, so you don't use the visibility keywords, public,
private, or protected.
Inheritance

Inheritance is one of the primary concepts of object-oriented programming. It allows you to reuse
existing code. Through effective employment of reuse, you can save time in your programming.
When programming for a large scale application, you often creates many classes in a single
program. Often you need classes with similar variables and functions to another existing class.
Inheritance enables classes to use the properties of other classes and add to those properties.
In PHP, classes can be extensions of other classes. The extended or derived class has all variables
and functions of the base class (this is called 'inheritance' despite the fact that nobody died) and
what you add in the extended definition.
In the following example, the shared class contains the $url property and show_url() method to
be inherited by schedule and bookstore class. The schedule class contains the show_sch()
function which gets the value of $str variable from shared class, and then add the
schedule.php<br> section to it. The $sch object is created to associate members of schedule class.
To derive one class from another, you use the extends keyword when declaring the derived class.
Notice that shared is the class that shares members, it is known as the base class. Remember, an
extended class is always dependent on a single base class, PHP does not support multiple
inheritance is not supported.
<?php
class shared {
public $url="http://www.cypresscollege.edu/";
public function show_url() {
echo $this->url . "<br>";
}
}
class schedule extends shared {
function show_sch() {
// get the shared property and add more string
echo $this->url . "schedule.php<br>";
}
}
class bookstore extends shared {
function __construct() {
// get the shared property and add more string
echo $this->url . "bookstore.php<br>";
}
}
$sch = new schedule();
$sch->show_url(); // call the shared function

PHP

216

$sch->show_sch(); // call the show_sch() function


$bks = new bookstore(); // call the __construct constructor
?>

Similarly, the bookstore class has a constructor that gets the value of $str variable from shared
class, and then add the bookstore.php<br> section to it. A constructor does not need the ->
operator to use the class member, as discussed in the previous section.
The output of the above code is:
http://www.cypresscollege.edu/
http://www.cypresscollege.edu/schedule.php
http://www.cypresscollege.edu/bookstore.php

It is good practice to define a generic class which can be used in all your projects and adapt this
class for the needs of each of your specific projects.
The rules are:
1. Classes are defined by the keyword class and then a block containing the methods and
attributes of the class.
2. A class is instantiated into an object using the keyword 'new', e.g.:
$myObj = new JabberWock();

3.
4.
5.

All attributes and methods of a class are public.


The class constructor has the same name as the class.
Class methods and attributes are accessed with the pointer operator, '->'. From the example
above:
$myObj->writePoem(); // member function.

Class and
Object
Functions

PHP also has many functions designed to handle class and objects. These functions provide a set of
tools that enable you to manipulate and obtain information about classes and objects. Using them,
you can find information about the object's class, with its methods and member variables.
The class_exists() function
The class_exists() function checks if the class has been defined. This function returns TRUE (or 1)
if the class given by class_name has been defined, FALSE (or 0) otherwise. For example:
<?php
class Color {
public $str1;
}
class Red extends Color {
public $str2;
}
echo
echo
echo
echo
?>

class_exists('Color')
class_exists('color')
class_exists('Red') .
class_exists('red') .

. "<br>"; //output is 1 or true


. "<br>"; //output is 1 or true
"<br>"; // output is 1 or true
"<br>"; // output is 1 or true

This function does not seem to be case-sensitive.


The get_class() function
PHP

217

The get_class() function returns the name of the class of an object. This function returns the name
of the class of which the object is an instance.
<?php
class Color {
public $str1;
}
$obj = new Color();
echo get_class($obj); // return Color
?>

The get_class_methods() function


The get_class_methods() function finds the names of the methods for a given class and returns
them as an array. Array containing the name(s) of an object's method(s); NULL if class_name is
not the name of a defined class. For example:
<?php
class Color {
public $str="red";
function upcase() {
strtoupper($this->str);
}
function Show_Color() {
echo $this->str;
}
}
print_r(get_class_methods('Color'));
?>

The output looks like:


Array ( [0] => upcase [1] => Show_Color )

The get_class_vars() function


This function will return an associative array of default properties of the class. The resulting array
elements are in the form of varname => value.
<?php
class car {
public $color="red";
public $year="2006";
public $model="ES330";
}
print_r(get_class_vars("car"));
?>

The output looks like:


Array ( [color] => red [year] => 2006 [model] => ES330 )

Review
Questions

PHP

1. Which will declare a class called emptyClass() that has no methods or properties?
A. $obj = class emptyClass { };
B. $obj = new emptyClass( );
C. $obj = new class emptyClass();
D. class emptyClass { }

218

2. Given a class called emptyClass(), which will create an object that is an instance of it?
A. $obj->emptyClass();
B. $obj = new emptyClass( );
C. obj.emptyClass();
D. obj->emptyClass();
3. Which declares a property within a class called Point?
A. class Point { var $x = 0; }
B. class Point { property $x = 0; }
C. class Point { $x->property = 0; }
D. None of the above
4. Which is a valid name for a constructor method?
A. construct;
B. __construct();
C. ___construct();
D. ->construct();
5. Which will prevent a method from being accessed except from within the current class and child
classes?
A. public function a( ) { }
B. protected function a( ) { }
C. private function a( ) { }
D. empty function a() { }
6. Given the following code segments, the $this __.
function getName() {
return $this->name;
}

A. refers to the currently instantiated object.


B. refers to the getName() function.
C. refers to the class the getName() function belongs to.
D. refers to the program itself
7. Given the following code segment, __.
private $name;

A. The $name variable is accessible to all classes.


B. The $name variable is accessible to all subclasses.
C. The $name variable is available only to the containing class.
D. The $name variable is available only to the containing subclasses.
8. In the following code segment, __.
class john extends jane {
function __construct() {
parent::__construct();
}
}

A. parent::__construct() is a constructor defined in john.


B. parent::__construct() is a constructor called by jane.
C. jane is the parent class, while john is the child class.
D. john is the parent class, while jane is the child class.

PHP

219

9. Given the following code segment, __.


&lt;?php <br>
class Item { <br>
var $name = "item"; <br>
<br>
function getName() { <br>
return "item"; <br>
} <br>
}<br>
<br>
$item = new Item ();<br>
print $item->getName ();<br>
?&gt;

A. Item is the name of class


B. the -> operator call an object method
C. getName is one of the methods
D. All of the above
10. Assuming there is a class named "Cart", which instantiate an object to the "Cart" class?
A. $cart = new Cart;
B. $cart => new Cart;
C. $cart -> new Cart;
D. $cart => new Cart();

PHP

220

Lab #13

PHP Objects and classes

Important, must read!!!


In order to avoid compatibility, I prepared two version of codes. The following codes are written for PHP 5 engine.
If your server runs on PHP4 engine, use the codes in Appendix A.
Learning Activity #1: Creating classes and use it with an object and a constructor
Objective: This activity is designed to explain how members in a given class may be accessed by constructor and
method. $obj1 calls the compensation class and it automatically executes the constructor. $obj2 calls the
compensation class, but the Manager() function must be triggered by using -> operator.
1.

In the X:\xampp\htdocs\myphp directory (create the myphp subdirectory if it does not exist), use Notepad
to create a new file named lab13_1.php with the following contents:
<?php
// programmer: Penn Wu
class compensation {
var $rate;
//constructor is executed when class is called
function compensation($salary) { //in PHP5 you can use __construct($salary)
$rate=0.02;
$this->rate = $rate * 0.1 * $salary;
echo "Regular employees pay $" . $this->rate . "<br>";
}
//method must be called
function Manager($salary) {
$rate=0.01;
$this->rate = $rate * 0.15 * $salary;
echo "Managers pay $" . $this->rate . "<br>";
}
}
// call the class and also execute constructor
$obj1=new compensation(90000);
// call the class and associate members to an object
$obj2=new compensation(70000); //constructor process 70000
$obj2->Manager(50000);
?>

2.

Test the program with a Apache server (XAMPP). The output looks like:

3.

Capture a screen shot similar to the above figure and paste it to a Word document named lab13.doc (or
lab13.docx).

Learning Activity #2: A Basic PHP Object-Oriented Application


PHP

221

Objective: This activity demonstrates how PHP OO is used in developing web application.
1.

In the X:\xampp\htdocs\myphp directory, use Notepad to create a new file named lab13_2.php with the
following contents:
<?php
// programmer: Penn Wu
if ($_POST)
{
class Bonus
{
var $rate=0.02;
var $bonus;
var $support=1000; //low income child support
var $merit; // merit points
var $salary; // annual salary
function Bonus($salary, $merit) { //in PHP5 you can use __construct()
if ($salary <=30000) { $salary += $this->support; }
// bonus = rate * (salary *( 1 + merit point/100) + child support
$this->bonus = $this->rate * ($salary * (1 + $merit/100) + $this->support);
echo "Your year-end bonus is $" . $this->bonus;
}
}
//call the class and auto-execute constructor
$class = new Bonus($_POST["salary"], $_POST["merit"]);
}
else
{
?>
<form action="<?php echo $_SERVER['PHP_SELF'];?>" method="post">
Enter<ol>
<li>Annual salary: <input type=text name="salary"> (e.g. 58000)
<li>Merit points [1-5]: <input type=text name="merit">
</ol>
<input type="submit" value="Calculate">
</form>
<?php
}
?>

2.

Test the program with a Apache server (XAMPP). A sample output looks like:

to

PHP

222

3.

Capture a screen shot similar to the above figure and paste it to a Word document named lab13.doc (or
lab13.docx).

Learning Activity #3: Dynamic web contents


Objective: This activity is designed to explain how PHP OO is useful in handling dynamic web contents. When a
user logs in using password "emp", "mgr", and "ceo", they are allowed to access different web content. This activity
use inheritance to determine what contents a user should see.
1.

In the X:\xampp\htdocs\myphp directory, use Notepad to create a new file named lab13_3.php with the
following contents:
<?php
// programmer: Penn Wu
class emp { //base class; superclass; parent class
var $psd;
var $content = "<p>Every employee can see this line..</p>";
var $link = "<p><a href='http://www.msn.com'>Benefit for all employees</a></p>";
function emp() { // in PHP you can use __construct()
echo $this->content;
echo $this->link;
}
}
class mgr extends emp { // derived; subclass; child class
//emp won't see this iframe
var $site="Stock option for <b>managers</b> only.";
function show() {
echo $this->site;
}
}
class ceo extends mgr { // derived; subclass; child class
//emp and mgr won't see this button
var $image="<p><button>Bonus for CEO only</button></p>";
function display() {
parent::show();
echo $this->image;
}
}
if ($_POST)
{
if ($_POST["psd"]=="emp") {
$obj = new emp;
}
else if ($_POST["psd"]=="mgr") {
$obj = new mgr();
$obj->show();
}
else if ($_POST["psd"]=="ceo") {
$obj = new ceo();
$obj->display();
}

PHP

223

else {
echo "You are not an authorized user.";
}
}
else
{
?>
<form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post">
Enter password: <input type="password" name="psd">
<input type="submit" value="Go">
</form>
<?php
}
?>

2.

Test the program with a Apache server (XAMPP) using password "emp", "mgr", and "ceo".

to
3.

Capture a screen shot similar to the above figure and paste it to a Word document named lab13.doc (or
lab13.docx).

Learning Activity #4: Using PHP class and class functions


1. In the X:\xampp\htdocs\myphp directory, use Notepad to create a new file named lab13_4.php with the
following contents:
<?php
// programmer: Penn Wu
class cis {
var $str1="good";
var $str2="luck";
}
class comp extends cis {
var $str3;
}
class ect extends cis {
function show() {
return $this->str1;;
}
}
if (class_exists('comp')==1) {
$obj = new cis();
echo "Comp is available in the <b>" . get_class($obj) . "</b> class.<br>";
}
echo "<p>Methods in array are: <b>";

PHP

224

print_r(get_class_methods('ect'));
echo "</b><p>Variables in array are: <b>";
print_r(get_class_vars("cis"));
echo "</b>";
?>

2.

Test the program with a Apache server (XAMPP). The output looks like:

3.

Capture a screen shot similar to the above figure and paste it to a Word document named lab13.doc (or
lab13.docx).

Learning Activity #5:


4. In the X:\xampp\htdocs\myphp directory, use Notepad to create a new file named lab13_5.php with the
following contents:
<?php
class User {
var $test;
var $test2;
}
$user1 = new User();
$user2 = new User();
$user1->test = "user1 is Jack";
$user1->test2 = "He is a student";
$user2->test = "user2 is Helen";
$user2->test2 = "She is a professor";
print_r($user1);
echo "<br />";
print_r($user2);
echo "<br />";
foreach($user1 as $key => $value)
$user2->$key = $value;
print_r($user1);
echo "<br />";
print_r($user2);
?>

5.

Test the program with a Apache server (XAMPP). The output looks like:

PHP

225

6.

Capture a screen shot similar to the above figure and paste it to a Word document named lab13.doc (or
lab13.docx).

Submitting the lab


1. Create a .zip file named lab13.zip containing:
Lab13_1.php
Lab13_2.php
Lab13_3.php
Lab13_4.php
Lab13_5.php
Lab13.doc (or .docx and make sure this file contains all the five screen shots)
2.

Upload the zipped file as response to question 11 or Assignment 13 (available in Blackboard).

PHP

226

Appendix A:
lab13_1.php
// for PHP4 engine
<?php
/*
============================================================
Code written by Penn Wu for students to learn PHP
and is Copyright (c) by Penn Wu unless otherwise stated.
============================================================
*/
class compensation {
var $rate;
//constructor is executed when class is called
function compensation($salary) { //in PHP5 you can use __construct($salary)
$rate=0.02;
$this->rate = $rate * 0.1 * $salary;
echo "Regular employees pay $" . $this->rate . "<br>";
}
//method must be called
function Manager($salary) {
$rate=0.01;
$this->rate = $rate * 0.15 * $salary;
echo "Managers pay $" . $this->rate . "<br>";
}
}
// call the class and also execute constructor
$obj1=new compensation(90000);
// call the class and associate members to an object
$obj2=new compensation(70000); //constructor process 70000
$obj2->Manager(50000);
?>

PHP

227

lab13_2.php
// for PHP4 engine
<?php
if ($_POST)
{
class Bonus
{
var $rate=0.02;
var $bonus;
var $support=1000; //low income child support
var $merit; // merit points
var $salary; // annual salary
function Bonus($salary, $merit) { //in PHP5 you can use __construct()
if ($salary <=30000) { $salary += $this->support; }
// bonus = rate * (salary *( 1 + merit point/100) + child support
$this->bonus = $this->rate * ($salary * (1 + $merit/100) + $this->support);
echo "Your year-end bonus is $" . $this->bonus;
}
}
//call the class and auto-execute constructor
$class = new Bonus($_POST["salary"], $_POST["merit"]);
}
else
{
?>
<form action="" method="post">
Enter<ol>
<li>Annual salary: <input type=text name="salary">
<li>Merit points [1-5]: <input type=text name="merit">
</ol>
<input type="submit" value="Calculate">
</form>
<?php
}
?>

PHP

228

lab13_3.php
// for PHP4 engine
<?php
if ($_POST)
{
class emp {
var $psd;
var $content = "<p>Every employee can see this line..</p>";
var $link = "<p><a href='pe1.htm'>Every employee can see this link</a></p>";
function emp() { // in PHP you can use __construct()
echo $this->content;
echo $this->link;
}
}
class mgr extends emp {
//emp won't see this iframe
var $site="<iframe width=100% src='http://www.msn.com'></iframe>";
function show() {
echo $this->site;
}
}
class ceo extends mgr {
//emp and mgr won't see this button
var $image="<p><button>Financial Statement</button></p>";
function display() {
parent::show();
echo $this->image;
}
}
if ($_POST["psd"]=="emp") {
$obj= new emp; }
if ($_POST["psd"]=="mgr") {
$obj=new mgr();
$obj->show();
}
if ($_POST["psd"]=="ceo") {
$obj=new ceo();
$obj->display();
}
}
else
{
?>
<form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post">
Enter password: <input type="password" name="psd">
<input type="submit" value="Go">
</form>
<?php
}
?>

PHP

229

lab13_4.php
// for PHP4 engine
<?php
class cis {
var $str1="good";
var $str2="luck";
}
class comp extends cis {
var $str3;
}
class ect extends cis {
function show() {
return $this->str1;;
}
}
if (class_exists('comp')==1) {
$obj = new cis();
echo "Comp is available";
echo "and it is in the " . get_class($obj) . "class.<br>";
}
print_r(get_class_methods('ect'));
echo "<br>";
print_r(get_class_vars("cis"));
?>

PHP

230

Lecture #14

Graphics in PHP

Introduction

You have learned to produce dynamic HTML using PHP. It is time to try to create graphics. PHP
has many graphic functions that can facilitate the drawing of lines, circles, manipulate image,
combined text, and other images. So, you can create dynamic graphics using PHP, too.

How to get
started

First you have to make sure you have php_gd.dll or php_gd2.dll in your extensions-folder, and next
you have to locate the same extension in the php.ini file. If the extension has ; in front of it or
something else, it is not active.

Basic PHP
graphics

The imagecreate() function creates a new palette based image, and its syntax is:
imagecreate(WidthValue, HeightValue);

which defines a blank area (square or rectangle) of WidthValue by HeightValue?


The imagecolorallocate() function defines a color for an image, and its syntax is:
imagecolorallocate(ResourceImage, RedValue, GreenValue, BlueValue);

where RedValue, GreenValue and BlueValue are the values of the red, green and blue component of
the requested color respectively. These parameters are integers between 0 and 255 or hexadecimals
between 0x00 and 0xFF.
The imageline() function draw a straight line. Its syntax is:
imageline(ResourceImage, x1, y1, x2, y2, Color);

which means it draws a line from (x1, y1) to (x2, y2). Notice that the top left is (0, 0) in a given image.
Once the image is created, you need to decision how they are outputted to the screen. This is done
by choosing an appropriate format such as gif, jpeg, or png. The imagepng() function output a PNG
image to either the browser or a file, imagegif() creates the GIF file in filename from the image, and
imagejpeg() creates the JPEG file in filename from the image.
Now consider the following code, it produces a white triangle inside a black area.
<?php
Header("Content-type: image/jpeg");
$image = ImageCreate(100,100);
$black = ImageColorAllocate($image, 0, 0, 0);
$white = ImageColorAllocate($image,255,255,255);
ImageLine($image, 0, 100, 50, 0, $white);
ImageLine($image, 50, 0, 100, 100, $white);
ImageLine($image, 0, 100, 100, 100, $white);
ImageJPEG($image);
ImageDestroy($image);
?>
<img src="<?=$_SERVER['PHP_SELF']; ?>">

When being executed, it looks like:

PHP

231

You might be wondering why the code contains the following line. It simply tells the browser that
whatever will be outputted should be treated as jpeg image.
Header("Content-type: image/jpeg");

This code choose to use the imagejpeg() function to turn the image into jpeg.
ImageJPEG($image);

The last line in the PHP code frees the memory that holds the code temporarily.
ImageDestroy($image);

The PHP part of code will not display the image. What you need to do to actually display you image
is to associate the above PHP code with an <img> HTML tag, which in turn loads the PHP code as
an image. The syntax is:
<img src=URL>

In the above example, the URL is referred to the PHP file itself, because the server environment
$_SERVER.
<img src="<?=$_SERVER['PHP_SELF']; ?>">

You can also use HTML hyperlink to link to this PHP file. Assuming that you saved the following
PHP code as a new file named myimg.php:
<?php
Header("Content-type: image/jpeg");
$image = ImageCreate(100,100);
// define background color to black
$black = ImageColorAllocate($image, 0, 0, 0);
// define color for lines
$white = ImageColorAllocate($image,255,255,255);
ImageLine($image, 0, 100, 50, 0, $white);
ImageLine($image, 50, 0, 100, 100, $white);
ImageLine($image, 0, 100, 100, 100, $white);
ImageJPEG($image);
ImageDestroy($image);
?>

You can then create another HTML file with the following line to display the image.
<html><body>
<img src="myimg.php">
</body></html>

With String
PHP

The imagestring() function adds a string horizontally starting with the upper-left corner. Its syntax

232

is:
imagestring(ResourceImage, font, x, y, String, Color)

where (x, y) is coordinates x, y with top left is (0, 0).


For example:
<?php
header("Content-type: image/png");
$img = imagecreate(200, 50);
// define background color to blue
$bColor = imagecolorallocate($img, 0, 0, 255);
// define text color
$textColor = imagecolorallocate($img, 212, 212, 212);
imagestring($img,5, 10, 10, "My PHP Graphic!", $textColor);
imagepng($img);
imagedestroy($img);
?>

will display a string inside the area, and it looks like:

Polygon

The imagepolygon() function creates a polygon image. Its syntax is:


imagepolygon(ResourceImage, ArrayPoints, num_points, Color);

where points is a PHP array in (x1, y1, x2, y2, ..., xn, yn) form. They specify the polygon's vertices (or
coordinates of angles).
For example:
<?php
// create a blank image
$image = imagecreate(300, 250);
// fill the background color
$bg = imagecolorallocate($image, 255, 0, 0);
// choose a color for the polygon
$col_poly = imagecolorallocate($image, 255, 255, 255);
// draw the polygon
imagepolygon($image,
array (
10, 10,
40, 50,
50, 150,
280, 200,
200, 150,
150, 50
), 6,
$col_poly);

This array defines the 6


vertices, while the 6 define the
polygon to be hexangular

// output the picture


header("Content-type: image/png");
imagepng($image);

PHP

233

?>

The output looks like:

Circle and
arc

The imagearc() function draws a partial ellipse centered at (cx, cy) with top left is (0, 0) in the
image. Its syntax is:
imagearc(ResourceImage, cx, cy, w, h, s, e, Color);

where W and h specifies the ellipse's width and height respectively while the start and end points are
specified in degrees indicated by the s and e arguments. 0 is located at the three-o'clock position,
and the arc is drawn clockwise.
For example:
<?php
header("Content-type: image/png");
// create a 200 by 200 image
$img = imagecreate(200, 200);
// allocate some colors
$white = imagecolorallocate($img, 255, 255, 255);
$black = imagecolorallocate($img, 0, 0, 0);
// draw a black circle
imagearc($img, 25, 25, 50, 50, 0, 360, $black);
// draw a black arc
imagearc($img, 100, 25, 50, 50, 0, 180, $black);
// output image in the browser
imagepng($img);
imagedestroy($img);
?>

The output looks like:

PHP

234

If you want to fill the circle, you need to use the imagefilledarc() function, which draws a partial
ellipse and fill it. Its syntax is:
imagefilledarc(ResourceImage, cx, cy, w, h, s, e, Color, Style);

where style is a bitwise OR of the following possibilities:


IMG_ARC_PIE - it produces a rounded edge.
IMG_ARC_CHORD - it just connects the starting and ending angles with a straight line.
IMG_ARC_NOFILL - it indicates that the arc or chord should be outlined, not filled.
IMG_ARC_EDGED - it, when used together with IMG_ARC_NOFILL, indicates that the
beginning and ending angles should be connected to the center.
For example:
<?php
header('Content-type: image/png');
// create image
$image = imagecreate(200, 200);
// allocate some colors
$white = imagecolorallocate($image, 0xFF, 0xFF, 0xFF);
$green = imagecolorallocate($image, 0x00, 0xFF, 0x00);
$blue = imagecolorallocate($image, 0x00, 0x00, 0xFF);
$red = imagecolorallocate($image, 0xFF, 0x00, 0x00);
imagefilledarc($image, 50, 50, 100, 100, 0, 45, $green,
IMG_ARC_PIE);
imagefilledarc($image, 50, 50, 100, 100, 45, 75 , $blue,
IMG_ARC_PIE);
imagefilledarc($image, 50, 50, 100, 100, 75, 360 , $red,
IMG_ARC_PIE);
imagepng($image);
imagedestroy($image);
?>

The output looks like:

Review
Questions

1. The __ function creates a new palette based image.


A. image_new()
B. new_image()
C. imagecreate()
D. imageset()
2. Which is a correct way to define the color of an image?
A. imagecolorallocate(525, 319, 1024);
B. imagecolorallocate(127, 215, 39);
C. imagecolorallocate(0x123, 0x124, 0x125);
D. imagecolorallocate(0h3a, 0h3b, 0h3c);
3. Which function outputs a GIF image to the browser?

PHP

235

A. imagegif()
B. image2gif()
C. imagetogif()
D. image_gif()
4. Which header declaration ensure that the image will be outputted as jpeg image?
A. Header("Content-type: photo/jpeg");
B. Header("Content-type: graphic/jpeg");
C. Header("Content-type: image/jpeg");
D. Header("Content-type: text/jpeg");
5. Which function converts an image to JPEG?
A. Image2JPEG()
B. ImageJPEG()
C. ImageToJPEG()
D. Image_JPEG()
6. Which frees the memory that holds the image?
A. ImageDestroy()
B. ImgDestroy()
C. Image_Destroy()
D. ImgDestroy()
7. The __ function adds a string horizontally starting with the upper-left corner.
A. imagetitle()
B. imagecaption()
C. imagestring()
D. imagelabel()
8. Given the following code, how vertices are there?
<pre>imagepolygon($image, <br>
array (10, 10, 40, 50, 50, 150, 280, 200, 200, 150), 5, <br>
$col_poly);</pre>

A. 4
B. 5
C. 6
D. 7
9. Given the following code, what is the coordinates of the center?
<pre>imagearc($img, 25, 25, 50, 50, 0, 360, $black);</pre>

A. (25, 25)
B. (50, 50)
C. (0, 360)
D. (25, 50)
10. Which indicates that the arc or chord should be outlined, not filled?
A. IMG_ARC_PIE
B. IMG_ARC_CHORD
C. IMG_ARC_NOFILL
D. IMG_ARC_EDGED

PHP

236

Lab #14

Graphics in PHP

Learning Activity #1:


1. In the X:\xampp\htdocs\myphp directory (create the myphp subdirectory if it does not exist), use Notepad
to create a new file named lab14_1.php with the following contents:
<?php
Header("Content-type: image/png");
$image = ImageCreate(400,400);
$white = ImageColorAllocate($image, 255, 255, 255);
$black = ImageColorAllocate($image, 0, 0, 0);
$red = ImageColorAllocate($image,255,0,0);
$green = ImageColorAllocate($image,0,255,0);
$blue = ImageColorAllocate($image,0,0,255);
ImageArc($image, 100, 100, 150, 150, 0, 360, $black);
ImageFilledArc($image, 200, 200, 50, 50, 0, 360, $black, IMG_ARC_PIE);
ImageRectangle($image, 60, 40, 10, 300, $blue);
ImageLine($image, 5, 390, 390, 10, $red);
imagefilledrectangle($image, 300, 150, 390, 380, $green);
ImagePNG($image);
ImageDestroy($image);
?>

2.

Test the program with a Apache server (XAMPP). The output looks like:

3.

Use Notepad to create new text file named lab14_1.htm with the following contents (to use the PHP image):
<html><body><img src="lab14_1.php" width=400 height=400></body></html>

4.
5.

Test the lab14_1.htm file.


Capture a screen shot similar to the above figure and paste it to a Word document named lab14.doc (or
lab14.docx).

Learning Activity #2:


1. In the X:\xampp\htdocs\myphp directory, use Notepad to create a new file named lab14_2.php with the
following contents:
<?php

PHP

237

if ($_POST)
{
$v1=$_POST['v1'];
$v2=$_POST['v2'];
$v3=$_POST['v3'];
$v4=$_POST['v4'];
Header("Content-type: image/png");
$image = ImageCreate(500,200);
$white = ImageColorAllocate($image, 255, 255, 255);
$black = ImageColorAllocate($image, 0, 0, 0);
$red = ImageColorAllocate($image,255,0,0);
$green = ImageColorAllocate($image,0,255,0);
$blue = ImageColorAllocate($image,0,0,255);
imagefilledrectangle($image,
imagefilledrectangle($image,
imagefilledrectangle($image,
imagefilledrectangle($image,
imagestring($image,
imagestring($image,
imagestring($image,
imagestring($image,

4,
4,
4,
4,

0,
0,
0,
0,

$v1+10,
$v2+10,
$v3+10,
$v4+10,

0, $v1, 19, $blue);


20, $v2, 39, $red);
40, $v3, 59, $green);
60, $v4, 79, $black);
0, $v1 . "(West Hills)", $black);
20, $v2 . "(Pomona)", $black);
40, $v3 . "(Long Beach)", $black);
60, $v4 . "(Irvine)", $black);

ImagePNG($image);
imageSaveAlpha("test1.png", true);
ImageDestroy($image);
}
else
{
?>
<form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post">
Enter values (between 0 and 400):<ol>
<li>West Hills: <input type="text" name="v1" size=5>
<li>Pomona: <input type="text" name="v2" size=5>
<li>Long Beach: <input type="text" name="v3" size=5>
<li>Irvine: <input type="text" name="v4" size=5>
</ol>
<input type="submit" value=" Plot ">
</form>
<?php
}
?>

2.

Test the program with a Apache server (XAMPP). A sample output looks like:

PHP

238

to

3.

Capture a screen shot similar to the above figure and paste it to a Word document named lab14.doc (or
lab14.docx).

Learning Activity #3:


1. In the X:\xampp\htdocs\myphp directory, use Notepad to create a new file named lab14_3.php with the
following contents:
<?php
if ($_POST)
{
$v1=round($_POST['POM']*360,0);
$v2=$v1+round($_POST['WH']*360,0);
$v3=$v2+round($_POST['LB']*360,0);
$p1
$p2
$p3
$p4

=
=
=
=

$_POST['POM'];
$_POST['WH'];
$_POST['LB'];
1 - ($p1+$p2+$p3);

header('Content-type: image/png');
// create image
$image = imagecreate(550, 400);
// allocate some solors
$white = imagecolorallocate($image, 0xFF, 0xFF, 0xFF);
$green = imagecolorallocate($image, 0x00, 0xFF, 0x00);
$blue = imagecolorallocate($image, 0x00, 0x00, 0xFF);
$red = imagecolorallocate($image, 0xFF, 0x00, 0x00);
$gray = imagecolorallocate($image, 0xC0, 0xC0, 0xC0);
$black = ImageColorAllocate($image, 0, 0, 0);
imagefilledarc($image,
imagefilledarc($image,
imagefilledarc($image,
imagefilledarc($image,

200,
200,
200,
200,

200,
200,
200,
200,

300,
300,
300,
300,

300,
300,
300,
300,

0, $v1, $green, IMG_ARC_PIE);


$v1, $v2 , $blue, IMG_ARC_PIE);
$v2, $v3 , $red, IMG_ARC_PIE);
$v3, 360 , $gray, IMG_ARC_PIE);

imagefilledrectangle($image, 360, 300, 375, 315, $green);


imagestring($image, 4, 380, 300, ($p1*100) . "% (Pomona)", $black);
imagefilledrectangle($image, 360, 320, 375, 335, $blue);
imagestring($image, 4, 380, 320, ($p2*100) . "% (West Hills)", $black);
imagefilledrectangle($image, 360, 340, 375, 355, $red);
imagestring($image, 4, 380, 340, ($p3*100) . "% (Long Beach)", $black);
imagefilledrectangle($image, 360, 360, 375, 375, $gray);
imagestring($image, 4, 380, 360, ($p4*100) . "% (Others)", $black);

PHP

239

// define text color


$black = imagecolorallocate($image,0,0,0);
imagestring($image,5, 150, 10, "Sales Revenue", $black);
imagepng($image);
imagedestroy($image);
}
else
{
?>
<form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post">
Enter percentage (between 0 and 1):<ol>
<li>Pomona: <input type="text" name="POM" size=5> [e.g. 0.45]
<li>West Hills: <input type="text" name="WH" size=5> [e.g. 0.25]
<li>Long Beach: <input type="text" name="LB" size=5> [e.g. 0.15]
<li>Others
</ol>
<input type="submit" value=" Plot ">
</form>
<?php
}
?>

2.

Test the program with a Apache server (XAMPP). The output looks like:

to

3.

Capture a screen shot similar to the above figure and paste it to a Word document named lab14.doc (or
lab14.docx).

Learning Activity #4:


1. In the X:\xampp\htdocs\myphp directory, use Notepad to create a new file named lab14_4.php with the
following contents:
<?php

You need 11 points to make 10 intervals for each line


// Add values to the graph lines
$RedPoint=array(8,37,153,91,242,178,296,169,71,153,65);
$BluePoint=array(18,33,58,127,165,194,247,259,273,199,165);
$GreenPoint=array(31,57,146,97,33,67,129,127,150,195,0);
// Define .PNG image

PHP

240

header("Content-type: image/png");
// Create image and define background and grid colors
$img=imagecreate(300, 300);
$white=imagecolorallocate($img, 255, 255, 255);
$black=imagecolorallocate($img, 0, 0, 0);

Coordinate (0,0) is the top-left


point of the grid, while (300,300) is
the bottom right one.

//define line colors


$red=imagecolorallocate($img, 255, 0, 0);
$blue=imagecolorallocate($img, 0, 0, 255);
$green=imagecolorallocate($img, 0, 255, 0);
// Create border around image
imageline($img, 0, 0, 0, 300, $black); // left border
imageline($img, 0, 0, 300, 0, $black); // top
imageline($img, 299, 0, 299, 299, $black); // right
imageline($img, 0, 299, 299, 299, $black); // bottom
// Create grid
for ($i=1; $i<=10; $i++){
imageline($img, $i*30, 0, $i*30, 300, $black);
imageline($img, 0, $i*30, 300, $i*30, $black);
}

The black grid lines are defined at a regular


interval of 30 pixels on both the x and y
axis (the dimensions of the image). There
are 10 lines on an x and y axis which equals
300 pixels.

To generate the line graph, you simply loop through the array to
// Create red line graph
figure out the start and end position of each line segment.
for ($i=0; $i<=10; $i++){
imageline($img, $i*30, (300-$RedPoint[$i]), ($i+1)*30, (300-$RedPoint[$i+1]),
$red);
}
// Create blue line graph
for ($i=0; $i<=10; $i++){
imageline($img, $i*30, (300-$BluePoint[$i]), ($i+1)*30, (300-$BluePoint[$i+1]),
$blue);
}
// Create green line graph
for ($i=0; $i<=10; $i++){
imageline($img, $i*30, (300-$GreenPoint[$i]), ($i+1)*30, (300-$GreenPoint[$i+1]),
$green);
}
// Output graph and clear image from memory
imagepng($img);
imagedestroy($img);
?>

2.

Test the program with a Apache server (XAMPP). It looks like:

PHP

241

3.

Capture a screen shot similar to the above figure and paste it to a Word document named lab14.doc (or
lab14.docx).

Learning Activity #5: Dynamically create bar chart


1. In the X:\xampp\htdocs\myphp directory, use Notepad to create a new file named lab14_5.php with the
following contents:
<?php
if ($_POST)
{
// retrieve value posted by the html form
$v1=$_POST['v1'];
$v2=$_POST['v2'];
$v3=$_POST['v3'];
$v4=$_POST['v4'];
$v5=$_POST['v5'];
$v6=$_POST['v6'];
$v7=$_POST['v7'];
$v8=$_POST['v8'];
$v9=$_POST['v9'];
$v10=$_POST['v10'];
$BarValues=array($v1,$v2,$v3,$v4,$v5,$v6,$v7,$v8,$v9,$v10);
// Define .PNG image
header("Content-type: image/png");
// Create image and define background and grid colors
$img=imagecreate(300, 300);
$white=imagecolorallocate($img, 255, 255, 255);
$black=imagecolorallocate($img, 0, 0, 0);
// define bar colors
$red=imagecolorallocate($img, 255, 0, 0);
$LiteRed=imagecolorallocate($img, 200, 0, 0);
// Create border around image
imageline($img, 0, 0, 0, 300, $black); // left border
imageline($img, 0, 0, 300, 0, $black); // top
imageline($img, 299, 0, 299, 299, $black); // right
imageline($img, 0, 299, 299, 299, $black); // bottom
// Create grid

PHP

242

for ($i=1; $i<=10; $i++){


imageline($img, $i*30, 0, $i*30, 300, $black);
imageline($img, 0, $i*30, 300, $i*30, $black);
}
// Create bar charts
for ($i=0; $i<10; $i++){
imagefilledrectangle($img, $i*30, (300-$BarValues[$i]), ($i+1)*30, 300, $LiteRed);
imagefilledrectangle($img, ($i*30)+1, (300-$BarValues[$i])+1, (($i+1)*30)-5, 298,
$red);
}
// Output graph and clear image from memory
imagepng($img);
imagedestroy($img);
}
else
{
?>
<form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post">
Enter values (between 0 and 300):<ol>
<li>Value 1: <input type="text" name="v1" size=5>
<li>Value 2: <input type="text" name="v2" size=5>
<li>Value 3: <input type="text" name="v3" size=5>
<li>Value 4: <input type="text" name="v4" size=5>
<li>Value 5: <input type="text" name="v5" size=5>
<li>Value 6: <input type="text" name="v6" size=5>
<li>Value 7: <input type="text" name="v7" size=5>
<li>Value 8: <input type="text" name="v8" size=5>
<li>Value 9: <input type="text" name="v9" size=5>
<li>Value 10: <input type="text" name="v10" size=5>
</ol>
<input type="submit" value=" Plot ">
</form>
<?php
}
?>

2.

Test the program with a Apache server (XAMPP). A sample output looks like:

to

3.

Capture a screen shot similar to the above figure and paste it to a Word document named lab14.doc (or
lab14.docx).

Submitting the lab


PHP

243

1.

Create a .zip file named lab14.zip containing:


Lab14_1.php
Lab14_2.php
Lab14_3.php
Lab14_4.php
Lab14_5.php
Lab14.doc (or .docx and make sure this file contains all the five screen shots)

2.

Upload the zipped file as response to question 11 or Assignment 14 (available in Blackboard).

PHP

244

Вам также может понравиться