Chapter 2-PHP
Chapter 2-PHP
Over the past few years, PHP and server-side Java have gained
momentum, while ASP has lost its share.
Introduction to PHP…
PHP is a server-side scripting language, which means that the scripts
are executed on the server, the computer where the Web site is
located.
This is different than JavaScript, another popular language for
dynamic Web sites.
JavaScript is executed by the browser, on the user’s computer.
Thus, JavaScript is a client-side language.
Software producers integrate the three software and offer them as bundle.
Some of such bundles are:
Vertrigo(Apache, PHP, Mysql)
Wamp (Windows) (Apache, Mysql, PHP)
Xampp(Apache, Mysql, PHP, Perl)
Lamp (Linux)(Apache, PHP, Mysql)
PHP files are executed through the web server only, not directly
http://127.0.0.1/test.php
Writing PHP
You add PHP code to your web page by using tags, similar to other
tags in the HTML file.
The PHP code section is enclosed in PHP tags with the following form:
<?php
PHP statements
?>
For example, you can add the following PHP section to your HTML
file.
<?php
echo “This line brought to you by PHP”;
?>
Web pages that contains PHP should be saved with .php extension.
You can also add several PHP sections to a Web page.
Writing PHP…
There are actually four different styles of PHP tags we can use.
Short style
<?
echo “<p>Order processed. </p>”;
?>
This style of tag is the simplest and follows the style of an SGML.
To use this tag, you either need to enable short tags in your config
file (short_open_tag = On), or compile PHP with short tags enabled.
XML style
<?php
echo “<p>Order processed. </p>”;
?>
This style of tag can be used with XML documents.
Most commonly used tag in literatures
Writing PHP…
SCRIPT style
<SCRIPT LANGUAGE=”php”>
echo “<p>Order processed. </p>”;
</SCRIPT>
This style of tag is the longest and will be familiar if you’ve used
JavaScript.
ASP style
<%
echo “<p>Order processed. </p>”;
%>
This style of tag is the same as used in Active Server Pages (ASP).
It can be used if you have enabled the asp_tags configuration
setting.
Writing PHP…
Example: your first hello world PHP script
<html>
<head><title>Hello World Script</title></head>
<body>
<?php
echo “<p>Hello World!</p>”
?>
</body>
</html>
We use the action attribute to specify the PHP to execute when the web page is
submitted.
<form name=”formname” method=”submitingmethod” action=”phpfile.php”>
form elements
</form>
For example:
$age = 21;
$price = 20.52;
$temperature = -5;
$name = “Clark Kent”;
echo “Your age is $age”;
1.2 Working with Variables…
PHP has a total of eight types: integers, doubles, Booleans,
strings, arrays, objects, NULL, and resources:
Integers are whole numbers, without a decimal point, like 495.
Doubles are floating-point numbers, like 3.14159 or 49.0.
Booleans have only two possible values: TRUE and FALSE.
Strings are sequences of characters, like “PHP is very interesting”.
Arrays are named and indexed collections of other values.
Objects are instances of programmer-defined classes.
Resources are special variables that hold references to resources
external to PHP such as database connections.
NULL is a special type that only has one value: NULL.
1.2 Working with Variables…
PHP is a loosely typed language.
This means that a single variable may contain any type of
data.
This could be a number, a string of text, or some other kind of
value, and may change types over its lifetime.
Example:
$testvar = 3 + 4;
echo “The value is $testvar”; //output: The value is 7
$testvar = “three”;
echo “The value is $testvar”; //output: The value is three
1.2 Working with Variables…
Displaying variable values
You can display the value stored in a variable with print statement. You can
output the value of a variable as in the following statements:
$today = “Sunday”;
print(“The day today is $today”);
The output from the preceding statements is “The day today is Sunday”.
Removing Variables
You can uncreate the variable by using this statement:
unset($age);
You can test for a negative, as well, by using not operator (!) in
front of the expression.
For example, the following statement returns TRUE if the
variable does not exist at all:
!isset($varname)
1.2 Working with Variables…
<?php
$a = "test";
$b = "anothertest";
echo isset($a); // TRUE
echo isset($a, $b); //TRUE
unset ($a);
echo isset($a, $b); //FALSE
$foo = NULL;
print isset($foo); // FALSE
$var = 0;
if (empty($var)) // evaluates TRUE
echo '$var is either 0 or not set at all';
?>
1.2 Working with Variables…
Type casting
We often work with multiple data types at once.
$foo = 321.456;
settype($foo, "string");
print("<br>String: $foo"); //output: String: 321.456
For example, to set a constant with the weather, use the following
statement:
define(“PI”,”3.141”);
This statement creates a constant called PI and sets its value to
“3.141”.
1.2 Working with Variables…
unlike variables, constant names do not begin with a dollar sign ($).
By convention, constants are given names that are all uppercase
so you can see easily that they’re constants.
However, PHP accepts lowercase letters without complaint.
Constants should not be given names that are keywords for PHP.
Keywords are words that have meaning for PHP, such as echo, and
they can’t be used as constants because PHP treats them as the PHP
feature of the same name.
1.2 Working with Variables…
Displaying constants
You can determine the value of a constant by using print as follows:
print(INTEREST);
$num = 33;
(boolean) $num;
echo $num;
Output: 33
echo gettype("4");
Output: String
1.3 Using Operators
PHP supports many operators.
Mathematical Operators
Arithmetic operators are straightforward—they are just the
However, if the ++ is after the $a, we are using the postfix increment operator.
This has a different effect.
$a=4;
echo $a++;
In this case, first, the value of $a is returned and printed, and second, it is
incremented.
The value that is printed is 4.
However, the value of $a after this statement is executed is 5.
1.3 Using Operators…
conditions.
For example, we might be interested in a case where the value
operator description
xor Is true if either (but not both) of its arguments are true
! Is true if its single argument (to the right) is false and false if its argument is true
You should give the if statement a condition that is evaluated to true or false.
By providing a sequence of conditions, the program can check each until it finds one
that is true.
You set the beginning value for the counter, set the ending value, and
set how the counter is incremented/decremented.
The general format is as follows:
Example:
for ($i = 1; $i <= 3; $i++) {
echo “$i. Hello World!<br>”;
}
You can nest for loops inside of for loops.
Suppose you want to print out the times tables from 1 to 9.
1x1=1
...
1x9=9
2x1=2
...
2 x 9 = 18
…
9x1=9
…
9 x 9 = 81
1 2 3 4 5 6 7 8 9
2 4 6 8 10 12 14 16 18
3 6 9 12 15 18 21 24 27
4 8 12 16 20 24 28 32 36
5 10 15 20 25 30 35 40 45
6 12 18 24 30 36 42 48 54
7 14 21 28 35 42 49 56 63
8 16 24 32 40 48 56 64 72
9 18 27 36 45 54 63 72 81
<html >
<head>
<title>Multiplication Table</title>
</head>
<body>
<h2>Multiplication Table</h2>
<?php
echo "<table border=\"1\">";
for ($row=1; $row<=9; $row++)
{
echo "<tr>";
for ($col=1; $col<=9; $col++){
$x=$col * $row;
echo "<td>$x</td>”;
}
echo "</tr>";
}
echo "</table>";
?>
</body>
</html>
1.5 Using Loops…
1.5.2 while loop
One of PHP looping construct is while, which has the following
syntax:
while (condition)
{
statement
}
output:
i is 1
i is 1
...
The variable $i is not incremented in the body of the while loop.
As a result, the value of $i is always 1 making the while condition,
$i<10, always true.
1.5 Using Loops…
Breaking out of a loop
Sometimes you want your script to break out of a loop.
Creating Arrays
There are different ways to create an array in a PHP script:
by assigning a value into one (and thereby implicitly creating it),
by using the array() construct, or
by calling a function that happens to return an array as its value.
The simplest way to create an array is to act as though a variable is already an array and
assign a value into it.
Example: the following code will create an array called $products by assigning value:
$products[0] = “Tires”;
$products[1] = “Oil”;
$products[2] = “Spark Plugs”;
$products[3] = “battery”;
$products[4] = “jar”;
1.6 Arrays…
If $products array does not already exist, the first line will create a new
array with just one element.
The subsequent lines add values to the array.
Associative Arrays
PHP also supports associative arrays.
The four keys in the $person array are called name, occupation, age,
and special power.
The associated values are Bob, engineer, 30, and x-ray vision.
You can reference specific elements of an associative array using the
specific key.
print_r($products);
Multidimensional Arrays
Arrays do not have to be a simple list of keys and values—each
location in the array can hold another array.
This way, we can create a two-dimensional array.
The following code results in the array being sorted into ascending
alphabetical order:
$products = array( “Tires”, “Oil”, “Spark Plugs” );
sort($products);
Output:
Oil, Spark Plugs, Tires.
The following code creates an associative array and then sorts the array
into ascending price order.
$prices = array( “Tires”=>100, “Oil”=>10, “Spark Plugs”=>4 );
asort($prices);
$prices = array( “Tires”=>100, “Oil”=>10, “Spark Plugs”=>4 );
ksort($prices);
1.6 Arrays…
Example:
$capitals[1] = “Sacramento”;
$capitals[2] = “Austin”;
$capitals[3] = “Salem”;
rsort($arrayname) Sorts by value in reverse order; assigns new numbers as the keys.
natsort($arrayname) Sorts mixed string/number values in natural order. For example, given an
array with values day1, day5, day11, day2, it sorts into the following order:
day1, day2, day5, day11. The previous sort functions sort the array into this
order: day1, day11, day2, day5.
1.6 Arrays…
Determining Size of Array
You can find out the size of your array by using either the count statement
or a sizeof statement.
The format for these statements is as follows:
$n = count($arrayname);
$n = sizeof($arrayname);
After either of these statements, $n will contain the number of elements in
the array.
Built-in Arrays
PHP has several built-in arrays that you can use when writing PHP scripts.
For example, information about your server (such as headers, paths, and
script locations) is stored in an array called $_SERVER
Array Description
$GLOBALS Contains all the global variables. For example, if you use the statement, $testvar = 1, you can
then access the variable as $GLOBALS [‘testvar’].
$ _POST[] Contains all the variables contained in a form if the form uses method=”post”.
$_REQUEST Contains all the variables together that are in $_POST, $_GET, and $_SESSION.
$_ENV Contains information provided by your operating system, such as the operating system name,
the system drive, and the path to your temp directory. This info varies depending on your
operating system
$HTTP_ENV_VARS Same as $_ENV.
1.6 Arrays…
The $_SERVER and $_ENV arrays contain different
information, depending on the server and operating system
you’re using.
You can see what information is in the arrays for your
particular server and operating system by using the following
statements:
foreach($_SERVER as $key =>$value)
echo “Key=$key, Value=$value\n”;
The output includes such lines as the following:
Key=HTTP_HOST, Value=127.0.0.1
Key=HTTP_ACCEPT, Value=text/html,application/xhtml+xml, application/xml;q=0.9,*/*;q=0.8
Key=HTTP_ACCEPT_LANGUAGE, Value=en-us,en;q=0.5
Key=HTTP_ACCEPT_ENCODING, Value=gzip, deflate
Key=HTTP_ACCEPT_CHARSET, Value=ISO-8859-1,utf-8;q=0.7,*;q=0.7
Key=HTTP_CONNECTION, Value=keep-alive
Key=WINDIR, Value=C:\Windows
Key=SERVER_SIGNATURE, Value=
Key=SERVER_SOFTWARE, Value=Apache/2.2.17 (Win32) PHP/5.3.6
Key=SERVER_ADDR, Value=127.0.0.1
Key=SERVER_PORT, Value=80
Key=REMOTE_ADDR, Value=127.0.0.1
Key=DOCUMENT_ROOT, Value=C:/Program Files (x86)/VertrigoServ/www
Key=SERVER_ADMIN, Value=lata@jal.com
Key=SCRIPT_FILENAME, Value=C:/Program Files (x86)/VertrigoServ/www/environment.php
Key=REMOTE_PORT, Value=2005
Key=GATEWAY_INTERFACE, Value=CGI/1.1
Key=SERVER_PROTOCOL, Value=HTTP/1.1
Key=REQUEST_METHOD, Value=GET
Key=QUERY_STRING, Value=
Key=SCRIPT_NAME, Value=/environment.php
Key=PHP_SELF, Value=/environment.php
1.6 Arrays…
The PHP_SELF element shows the file that contains the
script that is currently running.
You can see the information in the $_ENV array by
using the phpinfo() statement with a 16 to specify the
environmental variables, as follows:
phpinfo(16);
1.6 Arrays…
Array functions
1.7 Functions in PHP
Applications often perform the same task at different points in the
script or in different scripts.
This is when functions come in handy.
A function is a group of PHP statements that perform a specific task.
You can use the function wherever you need to perform the task.
Defining Functions
You can create a function by putting the code into a function block.
Calling a function
The following line is the simplest possible call to a function:
functionName();
This calls a function called functionName that does not require
parameters.
This line of code ignores any value that might be returned by this
function.
1.7 Functions in PHP…
Most functions do require one or more parameters.
We pass parameters by placing the data or the name of a variable
holding the data inside parentheses after the function name.
A call to a function with a parameter resembles the following:
function_name(parameter);
The contents of $value have not changed because of the scope rules.
This code creates a variable called $value which contains 10 & calls the
function increment().
The variable $value in the function is created when the function is called.
One is added to it, so the value of $value is 11 inside the function, until the
function ends.
In calling code, the variable $value is a different variable, with global
scope, and therefore unchanged.
1.7 Functions in PHP…
The normal way that function parameters are called is called pass
by value.
When you pass a parameter, a new variable is created which
contains the value passed in.
It is a copy of the original.
You are free to modify this value in any way, but the value of the
original variable outside the function remains unchanged.
output:
inside the function, $var = contents
outside the function, $var = contents
1.7 Functions in PHP…
In PHP global variables must be declared global inside a function if they
are going to be used in that function.
<?php
$a = 1;
$b = 2;
function Sum() {
global $a, $b;
$b = $a + $b;
}
Sum();
echo $b;
?>
setcookie(“variable”,”value”);
The variable is the variable name, but you do not include the dollar
sign ($).
This statement stores the information only until the user leaves your
Web site.
mktime: This function returns a date and time in a format that the computer can
understand. You must provide the desired date and time in the following order: hour,
minute, second, month, day, and year. If any value is not included, the current value
is used.
It is safest to set the cookie with a date you are sure has already
expired:
setcookie("vegetable", "", time()-60);
You should also ensure that you pass setcookie() the same path,
domain, and secure parameters as you did when originally setting
the cookie.
1.8 Cookies and Sessions…
1.8.2 Session
A session is the time that a user spends at your Web site.
Users may view many Web pages between the time they enter your site and
leave it.
Often you want information to be available for a complete session.
After you create a session, the session variables are available for your use
on any other Web page.
To make session information available, PHP does the following:
PHP assigns a session ID number.
The number is a really long number that is unique for the user and that no one
could possibly guess. The session ID is stored in a PHP system variable named
PHPSESSID.
PHP stores the variables that you want saved for the session in a file on the server.
The file is named with the session ID number.
It’s stored in a directory specified by session.save_path in the php.ini file.
PHP passes the session ID number to every page.
1.8 Cookies and Sessions…
If the user has cookies turned on, PHP passes the session ID
by using cookies.
If the user has cookies turned off, PHP behavior depends on
whether trans-sid is turned on in php.ini.
PHP gets the variables from the session file for each new
session page.
Whenever a user opens a new page that is part of the
session, PHP gets the variables from the file by using the
session ID number that was passed from the previous page.
The variables are available in the $_SESSION array.
1.8 Cookies and Sessions…
Opening and closing sessions
You should open a session at the beginning of each Web page.
session_start();
Because sessions use cookies, if the user has them turned on,
session_start is subject to the same limitation as cookies.
That is, to avoid an error, the session_start function must be called
before any output is sent.
This means that it is must be the first line code in your program.
1.8 Cookies and Sessions…
You may want to restrict your site to users with a valid user ID and
password.
For restricted sessions that users log into, you often want users to log out
when they’re finished.
To close a session, use the following statement wherever to want to close the
session:
session_destroy();
If you want to stop storing any variable at any time, you can unset the variable by
using the following statement:
unset($_SESSION[‘varname’]);
1.8 Cookies and Sessions…
The following two scripts show how to use sessions to pass information from one
page to the next.
<?php
/* Script name: sessionTest1.php */
session_start();
$_SESSION[‘fullName’] = “David John Antony”;
?>
<html>
<head><title>Testing Sessions page 1</title></head>
<body>
<p>This is a test of the sessions feature.
<form action=”sessionTest2.php” method=”POST”>
<input type=”text” name=”form_var” value=”testing”>
<input type=”submit” value=”Go to Next Page”>
</form>
</body>
</html>
1.8 Cookies and Sessions…
In this script, a session is started and one session variable called
fullName is stored.
A form is also displayed with one text field where the user can enter
some text.
When the submit button from this form, labeled “Go to Next Page”
is clicked, the sessionTest2.php script runs.
<?php
/* Script name: sessionTest2.php */
session_start();
$session_var = $_SESSION[‘fullName’];
$form_var = $_POST[‘form_var’];
echo “session_var = $session_var<br>\n”;
echo “form_var = $form_var<br>\n”;
?>
1.8 Cookies and Sessions…
output:
session_var = “David John Antony”;
form_var = testing