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>
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>
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>
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>
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
PHP
PHP
Lab #1
Introduction to PHP
3.
4.
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.
8.
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
3.
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.
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).
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).
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).
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).
PHP
12
Lecture #2:
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\".";
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";
?>
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";
?>
PHP
16
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 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'
?>
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
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
18
PHP_AUTH_PW
PHP_AUTH_USER
PHP_SELF
REMOTE_ADDR
SCRIPT_FILENAME
SERVER_NAME
SERVER_PORT
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
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
A. CISDEpt.com
B. 207.125.11.110
C. SNMP
D. /usr/cis246/test.php
PHP
21
Lab #2
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 ...
PHP
22
2.
3.
Capture a screen shot similar to the above figure and paste it to a Word document named lab2.doc (or
lab2.docx).
2.
3.
Capture a screen shot similar to the above figure and paste it to a Word document named lab2.doc (or
lab2.docx).
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.
3.
Capture a screen shot similar to the above figure and paste it to a Word document named lab2.doc (or
lab2.docx).
2.
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).
2.
4.
Capture a screen shot similar to the above figure and paste it to a Word document named lab2.doc (or
lab2.docx).
PHP
25
Lecture #3:
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 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;
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;
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
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
27
<?php
$x = 15; $y = 12;
$x+=5; $y-=2; //$x incremented by 5; $y decremented by 2
echo $x . "<br>";
echo $y;
?>
===
!==
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
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!";
}
?>
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
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.
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
?>
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
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
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
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 ...
PHP
5;
($x += 5) . "<br />\n";
($x -= 2) . "<br />\n";
($x /= 4) . "<br />\n";
//add 5
//minus 5
//divided by 4
35
//multiplied by 3
2.
3.
Capture a screen shot similar to the above figure and paste it to a Word document named lab3.doc (or
lab3.docx).
// random number 50 ~ 99
PHP
36
2.
3.
Capture a screen shot similar to the above figure and paste it to a Word document named lab3.doc (or
lab3.docx).
PHP
37
2.
3.
Capture a screen shot similar to the above figure and paste it to a Word document named lab3.doc (or
lab3.docx).
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>";
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).
PHP
39
2.
3.
Capture a screen shot similar to the above figure and paste it to a Word document named lab3.doc (or
lab3.docx).
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";
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>";
?>
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.';
?>
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];
?>
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"] ."!";
?>
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
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
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
Review
Questions
A. 1
B. 2
C. 3
D. 4
PHP
46
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";
PHP
47
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")
); ?>
48
PHP
49
Lab #4
PHP Arrays
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 ...
$n[0]
$n[1]
$n[2]
$n[3]
.
.
.
.
'
'
'
'
is
is
is
is
$n[0]!<br>';
$n[1]!<br>';
$n[2]!<br>';
$n[3]!<br>';
PHP
50
$school["UCI"] . "<br>";
$school["UCLA"] . "<br>";
$school["UCD"] . "<br>";
$school["UCSD"] . "<br>";
?>
2.
3.
4.
Capture a screen shot similar to the above figure and paste it to a Word document named lab4.doc (or
lab4.docx).
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.
4.
Capture a screen shot similar to the above figure and paste it to a Word document named lab4.doc (or
lab4.docx).
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).
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>";
PHP
53
);
$w = date("D"); // textual representation of a day, three letters
echo "You need to teach <b>$class[$w]</b> today!<br>";
?>
2.
3.
Capture a screen shot similar to the above figure and paste it to a Word document named lab4.doc (or
lab4.docx).
2.
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).
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
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!;
}
?>
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
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:
}
?>
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";
PHP
62
}
?>
Review
Questions
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
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 ...
2.
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).
{
{
{
{
{
{
{
{
{
{
{
{
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
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).
"It's
"It's
"It's
"It's
"It's
"It's
"It's
"It's
"It's
"It's
"It's
"It's
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).
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).
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.
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).
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
}
?>
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
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>
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
$a is 7.
//output
$a[0] => 1.
$a[1] => 3.
$a[2] => 5.
$a[3] => 7.
//output
$a[one] => 1
$a[three] => 3
$a[five] => 5
$a[seven] => 7
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/>");
?>
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>";
}
?>
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
}
}
?>
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
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
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 ...
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).
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).
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).
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
84
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
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?";
}
?>
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?";
}
?>
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");
?>
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");
?>
PHP
88
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>");
}
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
nothing
nothing
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, ......
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!";
Similarly,
echo("Don't chase the rainbow!");
and
echo "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
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
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");
?>
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);
?>
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));
?>
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",".",","); ?>
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
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 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 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>";
}
?>
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
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"
95
Y
y
z
Z
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");
?>
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!";
?>
Other
useful
function
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");
Review
Questions
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
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 ...
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).
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).
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).
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).
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).
PHP
105
Lecture #8:
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
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 )
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!>>>>>>
For example, the following code will repeat the string "I Love you!" 100 times.
<?php
echo str_repeat("I love you!<br>", 100);
?>
For example:
<?php
$str="Government officials pleaded for international assistance to
PHP
108
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.
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 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
}
?>
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 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>";
?>
Displaying
Strings
PHP
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);
?>
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
will return:
Array ( [0] => a [1] => p [2] => p [3] => l [4] => e )
Data
implementati
on functions
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);
?>
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
?>
PHP
112
This is a sentence.
This is a sentence.
However, your web browser will automatically convert < and > 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_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);
?>
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
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>";
Substrings
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
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
?>
PHP
115
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>"; /
?>
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, "$");
?>
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 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
URLs and
Base64
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_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);
?>
Hashing
PHP
119
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>";
?>
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>";
?>
Consequently, the result displayed on a web browser will be (with HTML table):
PartNo
Review
Questions
Description
Qty
UnitPrice
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
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);
?>
PHP
122
A. c2FtYmE=
B. b3Jhbmdl
C. YXBwbGU=
D. a2Vpa28=
PHP
123
Lab #8
String Functions
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 ...
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).
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).
PHP
126
}
?>
</table>
</body>
</html>
2.
3.
Capture a screen shot similar to the above figure and paste it to a Word document named lab8.doc (or
lab8.docx).
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).
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).
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)
PHP
129
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
131
Lecture #9:
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>
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
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
?>
PHP
135
if (empty($_POST["telephone"])) { $err .=
required!"; }
echo $err;
}
else
{
?>
"<li>Telephone is
If you simply click the button without entering anything, the output looks like:
Error:
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"}
<?php
if ($_GET)
{
echo $_REQUEST["fn"];
}
else
{
?>
<?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
<?php
}
?>
<?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
Seattle
Houston
New York
Boston
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
PHP
140
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);
?>
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'!";
}
?>
PHP
142
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
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",
?>
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>";
?>
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
?>
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");
?>
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>";
?>
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)
?>
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
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
148
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
PHP
150
Lab #9
2.
3.
Capture a screen shot similar to the above figure and paste it to a Word document named lab9.doc (or
lab9.docx).
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.
to
6.
Capture a screen shot similar to the above figure and paste it to a Word document named lab9.doc (or
lab9.docx).
2.
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.
3.
Capture a screen shot similar to the above figure and paste it to a Word document named lab9.doc (or
lab9.docx).
PHP
154
<?php
if ($_POST)
{
$err=array();
if
if
if
if
if
if
if
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
2.
3.
Capture a screen shot similar to the above figure and paste it to a Word document named lab9.doc (or
lab9.docx).
PHP
156
Lecture #10
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!"; }
?>
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>";
?>
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
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"));
?>
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
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">
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
PHP
164
Lab #10
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).
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.
4.
Capture a screen shot similar to the above figure and paste it to a Word document named lab10.doc (or
lab10.docx).
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).
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.
4.
Capture a screen shot similar to the above figure and paste it to a Word document named lab10.doc (or
lab10.docx).
PHP
169
Lecture #11
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.
170
Examples
'cookiename' is called as $_COOKIE['cookiename']
Assuming the name is 'cookiename', this value is
retrieved through $_COOKIE['cookiename']
available.
secure
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");;
?>
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>
PHP
176
Lab #11
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).
PHP
177
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.
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).
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
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).
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();
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
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).
PHP
181
Lecture #12
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
.....
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
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
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!");
?>
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);
?>
184
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);
?>
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
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"
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"
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
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
PHP
192
</html>
<?php
}
?>
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"];
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
PHP
194
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"]);
}
PHP
195
Lab #12
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.
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.
PHP
198
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).
PHP
200
PHP
201
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).
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
PHP
203
3.
4.
5.
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.
PHP
204
3.
Test the program with a Apache server (XAMPP). A sample output looks like:
4.
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).
PHP
206
Lecture #13
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;
?>
On the other hands, the $apple object can use the show() function by associating the object name
PHP
210
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
Method
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
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;
?>
Method
Visibility
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();
?>
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();
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
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.
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') .
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
?>
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;
}
PHP
219
PHP
220
Lab #13
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).
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).
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).
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).
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).
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);
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']; ?>">
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)
Polygon
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);
PHP
233
?>
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);
?>
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);
Review
Questions
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
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.
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,
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).
=
=
=
=
$_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,
PHP
239
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).
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);
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.
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).
PHP
242
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).
243
1.
2.
PHP
244