Introduction
PHP is a server-side scripting language and interpreter that is
available on a wide range of platforms, including some versions of Apache,
and Microsoft's Internet Information Server (IIS). The original program
was called Personal Home Page Tools, which is where the initials PHP come
from. There are also a few other definitions of the name, mostly thought
up in retrospect. Some say that PHP is a recursive three letter acronym
meaning, PHP Hypertext Pre-processor. Another generally accepted
definition is Pre Hypertext Processor. The PHP script is embedded in the
Web page, and interpreted on the server before being sent to the client
who requested the page. PHP is open source, and may be downloaded from http://www.php.net/.
Getting Started
PHP scripts have the extension .php. The PHP script is placed between
the <?php and ?> delimiters. The script
that is placed between these delimiters is interpreted on the server into
HMTL, before being sent to the client. The client will receive a pure HTML
page.
Comments
You can comment your code using C++ type comments. The following shows
the syntax for inline comments (a comment on a single line), and block
comments (comments placed over several lines).
// This is an inline comment /* This is a block
comment placed over two or more lines */
Output
There are two basic statements to output text with PHP, either using
echo, or print.
Output Using echo
The text to be outputed follows the echo statement.
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML
4.01//EN" "http://www.w3.org/TR/html4/strict.dtd"> <html> <head> <title>Starting
PHP</title> <meta http-equiv="Content-Type"
content="text/html;
charset=ISO-8859-1"> </head> <body> <p> <?php
echo "Hello World<br>";
?> </p> </body> </html>
Output using print
The text to be outputed follows the print statement.
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML
4.01//EN" "http://www.w3.org/TR/html4/strict.dtd"> <html> <head> <title>Starting
PHP</title> <meta http-equiv="Content-Type"
content="text/html;
charset=ISO-8859-1"> </head> <body> <p> <?php
print "Hello World<br>";
?> </p> </body> </html>
PHP also offers a shothand way of outputting information, using the
<?= and ?> delimiters. The following example prints the variable
$name (passed from a form) to greet a user.
Hello <?=$name?>
PHP Information
The phpinfo function is useful for trouble shooting, providing the
version of PHP, and how it is configured.
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML
4.01//EN" "http://www.w3.org/TR/html4/strict.dtd"> <html> <head> <title>PHP
Information</title> <meta
http-equiv="Content-Type" content="text/html;
charset=ISO-8859-1"> </head> <body> <p> <?php
phpinfo();?> </p> </body> </html>
Variables & Operators
PHP supports the basic data types of strings, integers, double
precision floating point numbers, etc, but is a weakly typed language.
This means that variables are not tied to a specific data type, and may
take any of the data types. Variables are not declared in PHP, but must be
prefixed with a $ sign.
String concatenation is achieved in PHP using the dot (.) operator. The
following example uses a variable called anyDataType. The data type is
given a string literal, and an integer values. The output is displayed
using the dot operator to concatenate a break to each line printed.
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML
4.01//EN" "http://www.w3.org/TR/html4/strict.dtd"> <html> <head> <title>Using
Variables</title> <meta http-equiv="Content-Type"
content="text/html;
charset=ISO-8859-1"> </head> <body> <p> <?php //
Use several data types with one
variable $anyDataType = "Hello
world"; print $anyDataType .
"<br>"; $anyDataType =
64; print $anyDataType .
"<br>"; $anyDataType +=
1900; print $anyDataType .
"<br>"; ?> </p> </body> </html>
Operators
Arithmetic Operators
| Operator |
Description |
+ |
Unary plus, or addition. |
- |
Unary minus or subtraction. |
* |
Multiplication. |
/ |
Division. |
% |
Modulus (remainder from a divide operation). |
++ |
Increment (pre-increment if placed before the variable,
post-increment if placed after). |
-- |
Decrement (pre-decrement if placed before the variable,
post-decrement if placed after). |
Arithmetic Operator Examples
// Caluclate the sum of a and b $total = $a +
$b; // Calculate the difference between a and b $difference = $a -
$b; // Calculate the product of a and b $product = $a * $b; //
Calculate the quotient of a and b $quotient = $a / $b; // Calculate
the remainder when a is divided by b $remainder = $a % $b; //
Increment the value of a $a++; // Decrement the value of
b $b--; // The pre-inrecrement version $num = ++$a; // The
pre-decrement version $num = --$b;
Self Assignment
If an assignment is made that requires the value of the variable being
assigned to, PHP offers a convenient shortcut by placing the operator
immediately before the assignment operator.
$total += $a; // Equivalent to $total = $total +
$a; $difference -= $a; // Equivalent to $difference = $difference -
$a; $product *= $a; // Equivalent to $product = $product *
$a; $quotient /= $a; // Equivalent to $quotient = $quotient /
$a; $remainder %= $a; // Equivalent to $remainder = $remainder %
$a;
Relational Operators
Relational operators (sometimes called comparison operators) are used
to compare values in an expression. The return value will be either true
or false.
PHP Relational Operators
| Operator |
Description |
< |
Less than (eg. $x < 10). |
<= |
Less than or equal (eg. $x <= 10). |
== |
Equivalence (eg. $x == 10). |
> |
Greater than (eg. $x > 10). |
>= |
Greater than or equal (eg. $x >= 10). |
!= |
Not equivalent (eg. $x != 10). |
Logical Operators
Logical operators allow you to combine the results of multiple
expressions to return a single value that evaluates to either true or
false.
PHP Logical Operators
| Operator |
Description |
! |
Logical Not. For example, (!$x) will evaluate to
True if $x is zero. |
&& |
Logical And. For example, ($x > 4 && $y <=
10) will evaluate to True is $x is greater than
four and $y is less than or equal to ten. |
|| |
Logical Or. For example, ($x > 10 || $y > 10)
will evaluate to True is either $x or
$y are greater than ten. |
Programming Constructs
Structured programming is based around three basic constructs:
Sequence, Selection and Iteration. The Sequence construct is the simplest,
whereby statements are executed in the order they're found in the code.
Both the Selection and Iteration constructs require a Logical Test.
Logical tests can be performed on variables, literal values, calculations,
and results of functions The test will evaluate to either true or false.
Selection Constructs
The Selection constructs are used when the flow of execution may flow
down two or more paths.
The if Statement
The if statement is used to control the flow of execution
down one of two or more paths, depending on the result of a logical test.
Further conditions may be specified with else if, should previous
conditions be false, and else may be used should none of the above be
true. There is no semicolon at the end of an if statement.
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML
4.01//EN"
"http://www.w3.org/TR/html4/strict.dtd"> <html> <head> <title>Simple
if Statement</title> <meta http-equiv="Content-Type"
content="text/html;
charset=ISO-8859-1"> </head> <body> <p> <?php
$morning = date("I"); if ($morning ==
"1") print "Good morning <br>";
else print "Good
afternoon <br>";
?> </p> </body> </html>
If statements can be nested, and the combined with logical operators.
If more than one line should be executed should a condition be True,
the lines should be enclosed within curly braces.
if ($x == 10) { print "That's an
excellent result <br>"; print "You should be
extremely proud of yourself! <br>"; }
Note: A common mistake is to use the assignment operator instead of the
equality operator when checking for equivalence. The following statement
will always evaluate to True as x is assigned the value 10 which is a
non-zero number.
if ($x = 10)
The switch Statement
When there are many conditions, the switch statement can be used if the
values are discrete. The switch statement is easier to read than multiple
if statements when there are a large number of discrete values.
The switch statement can be used when multiple if statements become
messy and difficult to read. Each case statement is an entry point, and
execution will continue from that point unless a break statement is found.
The break statement causes the program to continue from the end of the
switch statement. Only discrete values may be used for the cases. The
default statement is used if none of the listed cases are True. There is
no semicolon at the end of the switch statement.
The following example prints the word for the numbers 1 to 10 passed
from a form to the PHP script.
simpleForm.html
<!DOCTYPE
HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"
"http://www.w3.org/TR/html4/strict.dtd"> <html> <head> <title>Basic
Form</title> <meta http-equiv="Content-Type"
content="text/html;
charset=ISO-8859-1"> </head> <body> <h1>Number
Converter</h1> <form id="selection" name="selection"
method="post" action="printNumber.php"> <p>
<input type="text" size="5" value=""
name="numWord"><br> <input type="submit"
value="Display Word"
name="convert"> </p> </form> </body> </html>
The following is the PHP script that is called from, simpleForm.html.
printNumber.php
<!DOCTYPE
HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"
"http://www.w3.org/TR/html4/strict.dtd"> <html> <head> <title>Number
to Word</title> <meta http-equiv="Content-Type"
content="text/html;
charset=ISO-8859-1"> </head> <body> <p> <?php
switch ($numWord) {
case 1: print "One
<br>"; break; case
2: print "Two <br>";
break; case 3:
print "Three <br>";
break; case 4: print "Four
<br>"; break; case
5: print "Five <br>";
break; case 6:
print "Six <br>";
break; case 7: print
"Seven <br>"; break;
case 8: print "Eight <br>";
break; case 9:
print "Nine <br>";
break; case 10: print "Ten
<br>"; break;
default print "Number not between 1 and 10
<br>";
} ?> </p> </body> </html>
Iteration Constructs
The Iteration constructs are used when a block of code is required to
be executed continually until a condition is met.
Pre-Condition Loops
Pre-condition loops allow for a condition to be tested at the start of
the loop. This type of loop is used when you only want to execute the
block of code should the condition be true. If there is more than one line
to be included in the iteration, it should be contained within curly
braces.
A semicolon is not added to the end of the while statement. If one is
added in error, then the block of code will be executed exactly once.The
following example uses a pre-condition loop to calculate the factorial of
a number (a number that is multiplied by every integer number below itself
down to 1).
simpleForm.html
< !DOCTYPE
HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"
"http://www.w3.org/TR/html4/strict.dtd"> <html> <head> <title>Basic
Form</title> <meta http-equiv="Content-Type"
content="text/html;
charset=ISO-8859-1"> </head> <body> <h1>Factorials</h1> <form
id="selection" name="selection" method="post"
action="printFactorial.php"> <p> <input
type="text" size="5" value="" name="num"><br>
<input type="submit" value="Display Factorial"
name="convert"> </p> </form> </body> </html>
The following is the PHP script that is called from, simpleForm.html.
printFactorial.php
<!DOCTYPE HTML
PUBLIC "-//W3C//DTD HTML 4.01//EN"
"http://www.w3.org/TR/html4/strict.dtd"> <html> <head> <title>Factorial</title> <meta
http-equiv="Content-Type" content="text/html;
charset=ISO-8859-1"> </head> <body> <p> <?php
$factorial = 1; // Use a
pre-condition loop to calculate the factorial while ($num
> 1) $factorial *= $num--;
print "Factorial: " .
$factorial; ?> </p> </body> </html>
Post-Condition Loops
Post-condition loops allow for a condition to be tested at the end of
the loop. This type of loop is used when you want to execute the block of
code at least once. If there is more than one line to be included in the
iteration, it should be contained within curly braces. The following
example increments the value of result at least once, and continues
incrementing result while it has a value less than 10. <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"
"http://www.w3.org/TR/html4/strict.dtd"> <html> <head> <title>Post
Condition Loop</title> <meta http-equiv="Content-Type"
content="text/html;
charset=ISO-8859-1"> </head> <body> <p> <?php
$result = 1; /*
Use a post-condition loop to increment the result
and continue incrementing the result while
it has a value less than 10
*/ do {
$result++; print $result .
"<br>"; } while ($result <
10); ?> </p> </body> </html>
Counted Loops
Counted loops are used when you know how many times you want to execute
a statement or a list of statements. A semicolon is not added to the end
of the for statement. If one is added in error, then the block of code
will be executed exactly once. The general syntax for a counted loop is:
for (initialisation_section; condition;
increment_section) { // List of
statements }
The parameters that the counted loop operates on are in three sections
separated by semicolons. The first section is for initialising any
variables, the second section has the condition, and the third section has
any increments required to implement the loop. If more than one variable
is to be used in either the initialisation_section or the
increment_section, then they are separated by commas. The condition must
evaluate to either true or false. Compounded conditions must be created by
using the logical operators. The following example uses a counted loop
passed from a form, and prints the prime numbers (a number divisible only
by itself and 1) between 1 and a number enetered by the user.
simpleForm.html
<!DOCTYPE
HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"
"http://www.w3.org/TR/html4/strict.dtd"> <html> <head> <title>Basic
Form</title> <meta http-equiv="Content-Type"
content="text/html;
charset=ISO-8859-1"> </head> <body> <h1>Prime
Numbers</h1> <form id="selection" name="selection"
method="post" action="displayPrimes.php"> <p>
<input type="text" size="5" value="" name="num"><br>
<input type="submit" value="Display Prime Numbers"
name="dispPrimes"> </p> </form> </body> </html>
The following is the PHP script that is called from, simpleForm.html.
displayPrimes.php
<!DOCTYPE
HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"
"http://www.w3.org/TR/html4/strict.dtd"> <html> <head> <title>Prime
Numbers</title> <meta http-equiv="Content-Type"
content="text/html;
charset=ISO-8859-1"> </head> <body> <p> <?php
print "The following are the prime numbers from 1 to " .
$num . "<br>"; for ($counter=1; $counter < $num;
$counter++) { $test =
$counter; $prime = 1;
while ($test-- > 2)
if (($counter % $test) == 0)
$prime = 0; if ($prime
== 1) print $counter . " is a
prime number <br>";
} ?> </p> </body> </html>
The foreach Construct
Arrays in PHP are associative. PHP provides a foreach construct to
iterate through an associative array in terms of the key/value pair in the
array. The keyword as is used to place the key/value pairs into the
special $key=>$value syntax. The following example
illustrates how to use the foreach construct to iterate through the
$GLOBAL array, a PHP array that is used to store the global
variables that your script can access.
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML
4.01//EN"
"http://www.w3.org/TR/html4/strict.dtd"> <html> <head> <title>Global
Array</title> <meta http-equiv="Content-Type"
content="text/html;
charset=ISO-8859-1"> </head> <body> <h1>Global
Array</h1> <p> <?php
foreach($GLOBALS as $key=>$value)
print $key . " = " . $value .
"<br>"; ?> </p> </body> </html>
Server Variables
All servers maintain a set of variables that provide information such
as where the user come from, and other useful information. You can access
these variables by name in PHP. For example, if you wanted to know the
link that the user clicked to get to the current page, you could use the
$_SERVER["HTTP_REFERER"] server variable. The following
example lists the referer, and the visitor's browser.
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML
4.01//EN"
"http://www.w3.org/TR/html4/strict.dtd"> <html> <head> <title>Server
Variables</title> <meta http-equiv="Content-Type"
content="text/html;
charset=ISO-8859-1"> </head> <body> <p> <?php
print "Referer: " . $_SERVER["HTTP_REFERER"] .
"<br>"; print "Browser: " .
$_SERVER["HTTP_USER_AGENT"].
"<br>"; ?> </p> </body> </html>
List of Server Variables
The $_SERVER array stores all of the server variables that
can be accessed. The $_SERVER variable is an associative
array that you could iterate using the foreach construct. The following
example lists each of the variables, and the associated value.
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML
4.01//EN"
"http://www.w3.org/TR/html4/strict.dtd"> <html> <head> <title>List
of Server Variables</title> <meta http-equiv="Content-Type"
content="text/html;
charset=ISO-8859-1"> </head> <body> <h1>List
of Server
Variables</h1> <p> <?php
foreach($_SERVER as $key=>$value)
print $key . " = " . $value .
"<br>"; ?> </p> </body> </html>
Form Data
When an HTML document has a form, the action attribute specifies the
name of the program to handle the form data. When a PHP document is
specified in the action attribute, the PHP document has access to the
named fields in the form. Each field is accessible from the PHP arrays
$_POST or $_GET. The variable chosen will depend
on whether the form's method attribute was get or post.
The following example uses a form to get the user's name and age. The
information is then displayed with a PHP document.
simpleForm.html
<!DOCTYPE
HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"
"http://www.w3.org/TR/html4/strict.dtd"> <html> <head> <title>User
Details</title> <meta http-equiv="Content-Type"
content="text/html;
charset=ISO-8859-1"> </head> <body> <h1>User
Details</h1> <form id="userDetails" name="userDetails"
method="post" action="welcome.php"> <p> Enter
your Name: <br> <input type="text" size="40"
value="" name="name"><br> Enter your Age:
<br> <input type="text" size="5" value=""
name="age"><br> <input type="submit"
value="Enter"
name="welcome"> </p> </form> </body> </html>
The following is the PHP script that is called from, simpleForm.html.
welcome.php
<!DOCTYPE HTML
PUBLIC "-//W3C//DTD HTML 4.01//EN"
"http://www.w3.org/TR/html4/strict.dtd"> <html> <head> <title>Welcome</title> <meta
http-equiv="Content-Type" content="text/html;
charset=ISO-8859-1"> </head> <body> <p> <?php
print "Welcome " . $_POST["name"] .
"<br>"; print "I see you are " . $_POST["age"] . "
years old!
<br>"; ?> </p> </body> </html>
Iterating through a Form collection
You may iterate through the form collection, using either of the server
variables, $_GET, and $_POST. The following
example uses $_POST variable to iterate through the form
shown above.
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML
4.01//EN"
"http://www.w3.org/TR/html4/strict.dtd"> <html> <head> <title>Display
Form Collection</title> <meta http-equiv="Content-Type"
content="text/html;
charset=ISO-8859-1"> </head> <body> <p> <?php
print "Posted variables: <br>";
reset ($_POST); while(list($key,$val) = each
($_POST)) print $key . " = " . $value .
"<br>"; ?> </p> </body> </html>
HTTP Headers
The header function is used to send raw HTTP commands over the HTTP
protocols. The function takes as parameters the command, and an optional
value of true or false to determine if the header should replace the
previous header. If the second parameter isn't provided, the header will
be replaced.
When to Call Headers
The HTTP headers must be called before anything is written to the page.
This basically means ensuring that the header command is at the top of the
script. Occasionally, you may be using include files which send header
information, which could cause a problem if anything has been written to
the page. In this case, use the output buffer commands,
ob_start() to start buffering, and
ob_end_flush() to end buffering. When output buffering is
used, nothing is sent to the client until until the complete page is
prepared on the server (or it's explicitly sent using one of the output
buffering commands). You can use the headers_sent function to determine if
the headers have been sent. The function returns a boolean value, TRUE if
they have been sent, otherwise FALSE.
Cache Control
You can use the header function to ensure that pages are not cached by
the client, or any proxy caches they go through. The Expires command
should be set to a date in the past. The Cache-Contol command is used with
HTTP/1.1, and the Pragma command is used for HTTP/1.0.
<?php header("Expires: Sat, 1 Jan 2000 00:00:00
GMT"); header("Last-Modified: " . gmdate("D, d M Y H:i:s") . "
GMT"); header("Cache-Control: no-store, no-cache,
must-revalidate"); header("Cache-Control: post-check=0, pre-check=0",
false); header("Pragma: no-cache"); print "This page won't be
cached"; ?>
Redirecting Visitors
The Location command may be used to redirect users to another page. In
HTTP/1.1, the URI must be an absolute address.
header("Location:
http://www.juicystudio.com/");
You can use the server variables to find this information, and prefix a
relative page name with this information. The following example tests for
a cookie called, "userName" to determine if the user is logged in. If
they're not, they are redirected to the login page.
<?php if (!isset($userName)) {
$redirect = "http://" . $HTTP_SERVER_VARS['HTTP_HOST'];
if (dirname($HTTP_SERVER_VARS['PHP_SELF']) != "/")
$redirect = $redirect .
dirname($HTTP_SERVER_VARS['PHP_SELF']) . "/"; $redirect =
$redirect . "login.php"; header("Location:
$redirect"); exit(); } // Rest of page
here. ?>
Basic HTTP Authentication
Basic HTTP authentication uses a simple challenge/response scheme to
ensure pages are protected on the server. When the request for the page is
made, the server replies with an unauthorised user (401) code in the
header. On receiving the code, the browser presents the visitor with a
dialog box to enter their username and password. This data is then sent to
the server for authentication. If the username and password sent to the
server are correct, the page will be displayed. The username and password
are kept in two global variables called, $PHP_AUTH_USER, and $PHP_AUTH_PW.
The following example checks for the presence of $PHP_AUTH_USER, and
$PHP_AUTH_PW. If these exist, and match the values guest/guest, the page
is displayed. The example could easily be extended to validate the
username and password from a file.
<?php if ((!isset($PHP_AUTH_USER)) ||
(!isset($PHP_AUTH_PW)) || ($PHP_AUTH_USER !=
"guest") || ($PHP_AUTH_PW != "guest")) {
header('WWW-Authenticate: Basic realm="Private Area"');
header("HTTP/1.1 401 Unauthorized"); print "This
page requires authorisation.";
exit(); } else { print "You're through to the
secret page, was the effort worth it?"; } ?>
Cookies in PHP
Setting Cookies
The world wide web is stateless, which means it remembers nothing about
you. The usual way of keeping track of user preferences is to use cookies.
If you are setting a cookie, you must do it before the headers are
written, so must be set at the very start of the document. Cookies are set
in PHP using the setcookie function.
setcookie(name, value, expire, path,
domain);
The cookies are not actually set in the page where they are written,
but will be set in any subsequent pages. The following example sets a
userName cookie, that expires after one hour.
<?php // Set a
cookie that expires in one hour setcookie("userName",
$name, time()+3600); ?> <!DOCTYPE HTML PUBLIC
"-//W3C//DTD HTML 4.01//EN"
"http://www.w3.org/TR/html4/strict.dtd"> <html> <head> <title>PHP
Cookies</title> <meta http-equiv="Content-Type"
content="text/html;
charset=ISO-8859-1"> </head> <body> <p> A
cookie was set on this page, and will be active when the client has
sent the cookie back to the
server. </p> </body> </html>
Reading Cookies
When a cookie is set, PHP uses the cookie name as a variable with the
appropriate value. Accessing a cookie is just a simple case of referring
to the cookie name as a variable. You can use the isset function to
determine if a cookie has been set. The following example tests if the
userName cookie has been set, and prints an appropriate message.
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML
4.01//EN"
"http://www.w3.org/TR/html4/strict.dtd"> <html> <head> <title>Accessing
a Cookie</title> <meta http-equiv="Content-Type"
content="text/html;
charset=ISO-8859-1"> </head> <body> <p> <?php
if (isset($userName))
print "Welcome " . $userName . "<br>";
else print "You are not logged in
<br>"; ?> </p> </body> </html>
Server-side includes
A server side include is a file that is included within the current
document on the server. This can save the developer a considerable amout
of time. If all of the pages on your site have a similar header, you can
include a single file containing the header into your pages. When the
header needs updating, you only update the one page, which is included in
all of the pages that use the header. As many include files may be used as
required.
In PHP, server side includes are achieved using the require statement.
The following example includes a banner that contains a logo and set of
links for the pages.
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML
4.01//EN"
"http://www.w3.org/TR/html4/strict.dtd"> <html> <head> <title>Server
Side Include</title> <meta http-equiv="Content-Type"
content="text/html;
charset=ISO-8859-1"> </head> <body> <?php
require("banner.html"); ?> <p> This page
contains a banner that may be incuded in any of the PHP files used on
this site. </p> </body> </html>
Printed from
http://www.developerfusion.com/show/3703/
You may not reproduce this in any form without written authorization
from the author آ© Copyright
1999-2001
DeveloperFusion.com |