Chapter - 1: Server Side Programming Using PHP
Chapter - 1: Server Side Programming Using PHP
1
3.1 SERVER SIDE SCRIPTING
It is a web technology that allows custom HTML to be delivered
to a client machine where the code that generates processed on the
web server
Server-side language code remains on the web server. After it has
been processed, the server sends only the output of the script to
the user as HTML format.
Some of the examples of server side scripting languages are
CGL,
ASP,
2
PHP, …
CONT . . .
Server-side language brings websites to life in the following
ways:
Uploading files through a web page
Reading and writing to files
Displaying and updating information dynamically
Sending feedback from your website directly to your
mailbox
Using a database to display and store information
Making websites searchable. Etc… 3
FIG. 2.1. HOW SERVER SIDE SCRIPTING WORK
WampServer: C:\wamp\www
EasyPHP: C:\EasyPHP\www
IIS: C:\inetpub\wwwroo
Why PHP?
Runson different platforms (Windows, Linux, Unix, etc.)
Compatible with almost all servers used today(Apache, IIS, etc.)
7
FREE to download from the official PHP resource: www.php.net
Cont…
Common uses of PHP
PHP performs system functions, i.e. from files on a system it
can create, open, read, write, and close them.
PHP can handle forms, i.e. gather data from files, save data to a
file, thru email you can send data, return data to the user.
Enable you add, delete, modify elements within your database
Access cookies variables and set cookies.
You to restrict users to access only some pages of your website.
It can encrypt data.
Characteristics of PHP
Five important characteristics make PHP's practical nature possible:
Simplicity, Efficiency, Security, 8
Flexibility, Familiarity
Cont…
PHP Environment Setup:
In order to develop and run PHP Web pages three vital
components need to be installed on your computer system.
Web Server - PHP will work with virtually all Web Server
software, including IIS but then most often used is freely
available Apache Server.
Database - PHP will work with virtually all database
software, including Oracle and Sybase but most commonly
used is freely available MySQL database.
PHP Parser - In order to process PHP script instructions a
parser must be installed to generate HTML output that can be
sent to the Web Browser. 9
Cont…
Download those tools for free from the following address
Apache:- http://httpd.apache.org/download.cgi
MySQL:- http://www.mysql.com/downloads/index.html
10
3.3 Syntax and Variables in PHP
The PHP parsing engine needs a way to differentiate PHP code
from other elements in the page. The mechanism for doing so is
known as 'escaping to PHP.' There are four ways to do this:
1) Canonical PHP tags: A most universally effective PHP tag style
<?php PHP code goes here ?>
2) Short-open (SGML-style) tags:
<? PHP code goes here ?>
3) ASP-style tags:
<% PHP code goes here %>
4) HTML script tags:
<script language="PHP“> PHP code goes here </script>
Mostly PHP scripting block starts with <? php and 11
ends with ?>
Cont…
A PHP scripting block can be placed anywhere in the document.
Each code line in PHP must end with a semicolon which is a
separator and used to distinguish one set of instructions from
another.
If you have PHP inserted into your HTML and want the web
browser to interpret it correctly, then you must save the file with a
.php extension.
PHP is case sensitive
PHP is whitespace insensitive means that it almost never matters
how many whitespace characters you have in a row
Commenting PHP Code:
Single-line comments: // comments gone here 12
}
Cont…
B) Loop statements
Loops in PHP are used to execute the same block of code a
specified number of times.
PHP supports following four loop types.
</BODY></HTML>
Cont…
Example 2:
Access array elements there is a loop statement For Each loop
will continue until it has gone through every item in the array.
<?php
$employeeAges;
$employeeAges["Lisa"] = "28";
$employeeAges["Jack"] = "16";
$employeeAges["Ryan"] = "35";
foreach( $employeeAges as $key => $value){
echo "Name: $key, Age: $value <br />";
}
?>
27
3.6 PHP Arrays
An array is a data structure that stores one or more similar type of
values in a single value.
There are three different kind of arrays and each array value is
accessed using an ID which is called array index.
Arrays can store numbers, strings and any object but their index
will be pre-presented by numbers. By default array index starts
from zero.
Numeric array - An array with a numeric index. Values are stored
and accessed in linear fashion
Associative array - An array with strings as index. This stores
element values in association with key values rather than in a strict
linear index order.
Multidimensional array - An array containing one or more arrays
28
and values are accessed using multiple indices
Cont…
Example 1: Numeric arrays // Second method to create array.
<html> $numbers[0] = "one";
<body> $numbers[1] = "two";
<?php $numbers[2] = "three";
/* First method to create array. */ $numbers[3] = "four";
$numbers = array( 1, 2, 3, 4, 5); $numbers[4] = "five";
foreach( $numbers as $value ) foreach( $numbers as $value )
{ {
echo "Value is $value <br />"; echo "Value is $value <br />";
} }
?>
</body>
</html> 29
Cont…
Example 2: Associative Arrays
<html><body>
<?php /* First method to associate create array. */
$salary = S("Mohammad”=> 2000,”Qadir”=> 1000,”Zara”=> 50);
echo "Salary of mohammad is ". $S[‘Mohammad‘]. <br/>";
echo "Salary of qadir is ". $S[‘Qadir']. "<br />";
echo "Salary of zara is ". $S[‘Zara']. "<br />";
/* Second method to create array. */
$sS['mohammad‘]="high“; $S['qadir‘]="medium“; $S['zara‘]="low";
echo "Salary of mohammad is ". $S['mohammad'] . "<br />";
echo "Salary of qadir is ". $S['qadir']. "<br />";
echo "Salary of zara is ". $S['zara']. "<br />“;
?>
30
</body>
</html>
Cont…
Example 3: Multidimensional Arrays
<html><body>
<?php
$marks = array(“Abe" => array("physics" => 35, "maths" => 30,),
"qadir" => array("physics" => 30, "maths" => 32,),
"zara" => array("physics" => 31,"maths" => 22,));
/* Accessing multi-dimensional array values */
echo "Marks for mohammad in physics : " ;
echo $marks['mohammad']['physics'] . "<br />";
echo "Marks for qadir in maths: “. $marks['qadir']['maths‘]. "<br
/>";
echo "Marks for zara in chemistry :”.$marks['zara']['chemistry‘].
"<br />"; 31
?>
3.7 PHP Strings
They are sequences of characters, like "PHP supports string
operations".
Example:
$string_1 = "This is a string in double quotes";
<?php
$string1="Hello World";
$string2="1234";
echo $string1 . " " . $string2;
32
?>
Cont…
Using the strlen() function:- the strlen() function is used to find the
length of a string.
Let's find the length of our string "Hello world!":
<?php
echo strlen("Hello world!");
?>
Using the strpos() function:- the strpos() function is used to search
for a string or character within a string.
If a match is found in the string, this function will return the position
of the first match. If no match is found, it will return FALSE.
Let's see if we can find the string "world" in our string:
<?php
echo strpos("Hello world!","world"); 33
?>
3.8 PHP Function
A function is just a name we give to a block of code that can be
executed whenever we need it.
A function is a piece of code which takes one more input in the
form of parameter and does some processing and returns a value.
</body></html>
Cont…
Function with parameter
PHP gives you option to pass your parameters inside a function
which work like variables inside your function.
The following function with parameter returns the sum of two
numbers.
<?php
function mySum($numX, $numY){
$total = $numX + $numY;
return $total;
}
$myNumber = 0;
echo "Before the function, myNumber = ". $myNumber ."<br />";
$myNumber = mySum(3, 4); // Store the result of mySum in $myNumber
36
echo "After the function, myNumber = " . $myNumber ."<br />";
?>
Cont…
Passing Arguments by Reference:
Reference to the variable is manipulated by the function rather than a
copy of the variable's value.
Any changes made to an argument in these cases will change the
value of the original variable.
You can pass an argument by reference by adding an ampersand to
the variable name in either the function call or the function definition.
Example:
<html>
<head>
<title>Passing Argument by Reference</title>
</head> 37
<body>
Cont…
<?php
function addFive($num)
{ $num += 5; }
function addSix(&$num)
{ $num += 6; }
$orignum = 10;
addFive( &$orignum );
echo "Original Value is $orignum<br />";
addSix( $orignum );
echo "Original Value is $orignum<br />";
?> 38
</body></html>
Cont…
PHP Functions returning value:
A function can return a value using the return statement in conjunction
with a value or object.
Return stops the execution of the function and sends the value back to
the calling code.
You can return more than one value from a function using return
array(1,2,3,4).
Example:
<html>
<head>
<title>Writing PHP Function which returns value</title>
39
</head>
<body>
Cont…
<?php
function addFunction($num1, $num2)
{
$sum = $num1 + $num2;
return $sum;
}
$return_value = addFunction(10, 20);
echo "Returned value from the function : $return_value
?>
</body>
</html> 40
Cont…
Setting Default Values for Function Parameters:
You can set a parameter to have a default value if the function's
caller doesn't pass it.
<html>
<head><title>Writing PHP Function which returns value</title>
</head><body>
<?php
function printMe($param = NULL)
{ print $param; }
printMe("This is test");
printMe(); ?> 41
</body></html>
Cont…
Dynamic Function Calls:
It is possible to assign function names as strings to variables and
then treat these variables exactly as you would the function name
itself.
Example: <html><head><title>Dynamic Function Calls</title>
</head><body>
<?php
function sayHello()
{ echo "Hello<br />“; }
$function_holder = "sayHello";
$function_holder(); 42
?> </body></html>
Cont…
Functions and Variable scope
Refers to where the value of a variable is accessible to
read/modify.
There are local and global scopes
Local scope is inside a function only
Global scope is everywhere except a function with the
exception of when it is imported into that function.
SuperGlobals are available by default inside and outside
functions i.e. $_POST, $_COOKIE, $_GET
Constants also have superglobal scope
The variable inside the function is totally separated from the
43
outside ones, so we can have variables having the same name
inside and outside the function but they are not the same.
Cont…
Example:
Unless we make a special declaration in a function the function
will not have access to global variables.
<?php
function customer(){
global $age; $age=21; $name="Abebe";
print "wel come $name. Are You still $age years old?";
}
customer();
echo $age;// $age is global variable so 21 will be here too
echo $name;// $name is local variable, Abebe will not be
displayed here
?> 44
Cont…
PHP - Predefined Variables
PHP provides a large number of predefined variables to any script
which it runs.
Also it provides an additional set of predefined arrays containing
variables from the web server the environment, and user input
which is called superglobals:
$GLOBALS: Contains a reference to every variable which is
currently available within the global scope of the script. The keys
of this array are the names of the global variables.
$_SERVER: This is an array containing information such as
headers, paths, and script locations. The entries in this array are
created by the web server. There is no guarantee that every web
server will provide any of these. See next section for a complete
45
<html><body>
<?php require(“xmenu.php"); ?>
<p>This example to show how to include wrong file!</p>
</body></html>
Note: You may get plain warning messages or fatal error messages52
Warning:
main(xmenu.php):
failed to open stream: No such file or directory in….
Fatal error: main():
Use include():- if your page would remain usable even without the
contents of the external file or the page you are including .
Use require():- if the page depends on the external file that means
53
if the page you are including is the core part of the website.
PHP WITH HTML FORMS
54
3.10 POST AND GET METHODS
Before the browser sends the information, it encodes it using a
scheme called URL encoding. In this scheme,
name/value pairs are joined with equal signs and
name1=value1&name2=value2&name3=value3
Spaces are removed and replaced with the + character and
hexadecimal values.
After the information is encoded it is sent to the server.
There are two ways the browser can send information to web server
• The GET Method
• The POST Method
Always use $_POST and $_GET when processing user input from 55
a form.
Cont…
A) POST Method
Transfers information via HTTP headers.
The information is encoded as described above and put into a
header called QUERY_STRING.
Does not have any restriction on data size to be sent.
It can be used to send ASCII as well as binary data.
The data sent by POST method goes through HTTP header so
security depends on HTTP protocol. By using Secure HTTP you
can make sure that your information is secure.
Syntax:- <form action="process.php" method=“POST">
HTML code specifies that the form data will be submitted to the
"process.php" web page using the POST method
PHP store all the "posted" values into an associative array 56
called "$_POST".
Cont…
The form names are used as the keys in the associative array.
Example: the following html page
<html>
<body>
<form action="process.php" method="post">
Name <input name="quantity" type="text" />
<input type=“submit” value=“submit”>
</form>
Then, process.php can retrieve data as follows,
$name=$_post[“name”];
Then u can use the name of the user for any purpose what u want.
</html>
Cont…
B) GET Method
It sends the encoded user information appended to the page
request.
The page and encoded information are separated by ?
Character.
http://www.test.com/index.htm?name1=value1&name2=value2
GET method is restricted to send up to 1024 characters only.
Never use GET method if you have password or other sensitive
information to be sent to the server.
GET can't be used to send binary data, like images or word
documents, to the server.
The data sent by GET method can be accessed using
QUERY_STRING environment variable. 59
The PHP provides $_GET associative array to access all the
sent information using GET method.
Cont…
Syntax:- <form action="process.php" method=“GET">
<html><body>
<form action="process.php" method="post">
<select name="item">option>Sugar</option>… </select>
<input name="quantity" type="text" />
<input type=“submit” value=“submit”></form>
It passes the variables along to the "process.php" web page by
appending them onto the end of the URL
After clicking submit, The URL would have this added on to the
end of it: "?item=##&quantity=##"
The question mark "?" tells the browser that the following items
are variables.
PHP code from "process.php" using $_GET is, 60
63
Cont…
The $_REQUEST variable
It contains the contents of both $_GET, $_POST, and $_COOKIE
and It can be used to get the result from form data sent with both
the GET and POST methods.
Example: <?php
<?php echo”<html><body>”;
echo”<form method=‘POST’>”;
echo”What is your name<input type=‘text’ name=‘name’>”;
echo”<input type=‘submit’ value=‘submit’>”;
$nm=$POST[“name”];
echo”welcome $nm”;
echo”</form>”; 65
echo”</body></html>” ; ?>
3.11VALIDATION
1) Retrieving Form Data - Setting up Variables
PHP provides a function called IsSet(“$var”) that tests a variable
to see whether it has been assigned a value.
And there is also empty(“$var”) function to check the value of the
variable whether it has a value or not.
Example: From the above example we can check the variable $name
value
if(!IsSet($name))
{ echo”Error”; }
OR
if(empty($name)){
echo'<script type="text/javascript">';
66
echo 'alert("Please fill all required information")';
echo'</script>'; }
Cont…
2) Accessing ComboBox, CheckBox and radio button value
Example: After filling the following registration form the data will
be processed in the server and display all the data back to the user.
<form name=”regfrm” action=”registration.php”
method=”POST”>
67
Cont…
Before retrieving the data Remember that All form elements has
their own value. <option value=”Maths”>Mathematics</option>
In the HTML page the checkbox name must be array like this,
<html>
<body>
<form name=”regfrm” action=”registration.php” method=”POST”>
<input type=”checkbox” name=”course[]”
value=”InternetProgramming”><br>
<input type=”checkbox” name=”course[]”
value=”DistributedSystem”><br>
<input type=”checkbox” name=”course[]”
value=”AdvancedProgramming”><br>
</form>
68
<body>
</html>
Cont…
Registration.php will have posted data as follows
<?php
$name = $_POST["name"];
$dept = $_POST["dept"];
$gender = $_POST["gender"];
$userName = $_POST["userName"];
$password = $_POST["password"];
$course = $_POST["course"];
We can validate whether they have value or not using the built in
validation PHP functions
69
Cont…
Then, the following page must be appear when the user clicks
Register button
….
echo”Wel come $name”;
echo”Here is your information:”;
echo”Department: $dept“;
echo”User Name: $userName”;
echo”Password: $password”;
echo”Favourite Courses are: <br>”;
$x=count($course);
For($a=0; $a<$x; $a++)
{ echo $course[$a] ."<br>“; }
include(“Login.html”); 70
?>
3.12 Cookies and Session in PHP
Both are use in terms of data storage in programming
1) Cookies
Are text files stored on the client computer and they are kept of use
tracking purpose.
Cookies are usually set in an HTTP header (although JavaScript
can also set a cookie directly on a browser).
If the browser is configured to store cookies, it will then keep
information such as name value pair, a GMT date, a path and a
domain until the expiry date.
If the user points the browser at any page that matches the path and
domain of the cookie, it will resend the cookie to the server.
A PHP script will then have access to the cookie in the
environmental variables $_COOKIE or $HTTP_COOKIE_VARS[]
71
which holds all cookie names and values
Cont…
Setting Cookies with PHP:
PHP provided setcookie() function to set a cookie.
This function requires up to six arguments
setcookie(name, value, expire, path, domain, security);
Setcookie() should be called before <html> tag and for each cookie
this function has to be called separately.
You can use isset() function to check if a cookie is set or not.
Name - This sets the name of the cookie and is stored in an
environment variable called HTTP_COOKIE_VARS which used
while accessing cookies.
Expiry - This specify a future time in seconds since 00:00:00
GMT on 1st Jan 1970. After this time cookie will become
inaccessible. If this parameter is not set then cookie will
72
</html>
Cont…
Example: Accessing Cookies with PHP
<html>
<head><title>Accessing Cookies with PHP</title>
</head><body>
<?php
if( isset($_COOKIE["name"]) && ( isset($_COOKIE[“age"]))
echo $_COOKIE["name"]. "<br />“; /* is equivalent to */
echo $HTTP_COOKIE_VARS["name"]. "<br />";
echo $_COOKIE["age"] . "<br />“; /* is equivalent to */
echo $HTTP_COOKIE_VARS["name"] . "<br />";
else
echo "Sorry... Not recognized" . "<br />";
?>
75
</body>
</html>
Cont…
Example: Deleting Cookie
<?php
setcookie( "name", "", time()- 60, "/","", 0);
setcookie( "age", "", time()- 60, "/","", 0);
?>
<html>
<head>
<title>Deleting Cookies with PHP</title>
</head>
<body>
<?php echo "Deleted Cookies" ?>
</body>
</html> 76
2) Session
An alternative way to make data accessible across the various
pages of an entire website.
Creates a file in a temporary directory on the server where
registered session variables and their values are stored.
The location of the temporary file is determined by a setting in the
php.ini file called session.save_path
When a session is started following things happen:
PHP first creates a unique identifier for that particular session
which is a random string of 32 hexadecimal numbers such as
3c7foj34c3jj973hjkop2fc937e3443.
A cookie called PHPSESSID is automatically sent to the user's
computer to store unique session identification string.
A file is automatically created on the server in the designated
77
temporary directory and bears the name of the unique identifier
prefixed by sess_ i.e. sess_3c7foj34c3jj973hjkop2fc937e3443.
Cont…
visitors are not able to edit Sessions since it stored on the server
Starting a PHP Session:
Easily started by making a call to the session_start() function
which first checks if a session is already started or not.
It is recommended to put the call to session_start() at the
beginning of the page(before the <html> tag).
Session variables are stored in associative array called
$_SESSION[]which can be accessed during lifetime of a
session.
Make use of isset() function to check if session variable is
already set or not.
If you wish to delete session data, use the unset() or the
session_destroy() function.
The unset() function is used to free the specified session 78
variable: unset($_SESSION['views']);
Cont…
Example: Start php session $msg .= "in this session.";
<?php ?>
session_start(); <html>
if( <head>
isset( $_SESSION['counter'] ) ) <title>Setting up a PHP
{ session</title>
$_SESSION['counter'] += 1; </head>
} <body>
else { <?php echo ( $msg ); ?>
$_SESSION['counter'] = 1; } </body>
$msg = "You have visited this </html>
page ". $_SESSION['counter'];
79
Cont…
isset() function to check if session variable is already set or not.
<?php
unset($_SESSION['counter']);
?>
You can completely destroy the session by calling the
session_destroy() function:
<?php
session_destroy();
?>
Note:
Sessions and Cookies are useful mechanism to control the state
of Login and Logout over website 80
3.13 PHP File Uploading
A PHP script can be used with a HTML form to allow users to
upload files to the server.
Initially files are uploaded into a temporary directory and then
relocated to a target destination by a PHP script.
Information in the phpinfo.php page describes
Temporary directory used for file uploads as upload_tmp_dir
Maximum permitted size of files uploaded as
upload_max_filesize.
These parameters are set into PHP configuration file php.ini
An uploaded file could be a text file or image file or any
document.
Usual when writing files it is necessary for both temporary and 81
The full path to the selected file appears in the text filed then
the user clicks the submit button.
The selected file is sent to the temporary directory on the server.
The PHP script that was specified as the form handler in the
form's action attribute checks that the file has arrived and then
copies the file into an intended directory.
82
</html>
Cont…
Creating an upload script:
A Global variable ‘$_FILES’ which is an associate two dimension
array and keeps all the information related to uploaded file.
So if the value assigned to the input's name attribute in uploading
form was file, then PHP would create following five variables:
$_FILES['file']['tmp_name']- the uploaded file in the
temporary directory on the web server.
$_FILES['file']['name'] - the actual name of the uploaded file.
$_FILES['file']['size'] - the size in bytes of the uploaded file.
$_FILES['file']['type'] - the MIME type of the uploaded file.
$_FILES['file']['error'] - the error code associated with this
84
file upload.
Cont…
Example: code for upload script
<?php
if( $_FILES['file']['name'] != "" )
{
copy( $_FILES['file']['name'], "/var/www/html" ) or
die( "Could not copy file!");
}
else{
die("No file specified!");
}
?>
85
Cont…
<html>
<head>
<title>Uploading Complete</title>
</head>
<body>
<h2>Uploaded File Info:</h2>
<ul>
<li>Sent file: <?php echo $_FILES['file']['name']; ?>
<li>File size: <?php echo $_FILES['file']['size']; ?>
bytes
<li>File type: <?php echo $_FILES['file']['type']; ?>
</ul>
</body> 86
</html>
3.14 PHP – Date and Time Functions
Allow you to get the date and time from the server where your
PHP scripts are running.
You can use these functions to format the date and time in many
different ways.
Function Description PHP
checkdate() Validates a Gregorian date 3
date_date_set() Sets the date 5
date_modify() Alters the timestamp 5
date_sunrise() Returns time of sunrise
for a given day/ location 5
date_sunset() Returns the time of sunset
for a given day / location 5
date_time_set() Sets the time 5 87
date() Formats a local time/date 3
Cont…
Function Description PHP
gmdate() Formats a GMT/UTC date/time 3
idate() Formats a local time/date as integer 5
microtime() Returns microseconds for current time 3
time() Returns the current time as a
Unix timestamp 3
timezone_name_get() Returns the name of
the timezone 5
timezone_offset_get() Returns the timezone
offset from GMT 5
timezone_open() Returns new
DateTimeZone object 5
timezone_transitions_get() Returns all transitions 88
Example:
Expression Description
[0-9] It matches any decimal digit from 0 through 9.
[a-z] It matches any character from lowercase
a through lowercase z.
[A-Z] It matches any character from uppercase
A through uppercase Z.
[a-Z] It matches any character from lowercase 90
a through uppercase Z.
Cont…
2) Quantifiers:
The frequency or position of bracketed character sequences and
single characters can be denoted by a special character.
Each pecial character having a specific connotation.
Example:
Expression Description
p+ It matches any string containing at least one p.
p* It matches any string containing zero or more p's.
p? It matches any string containing zero or one p's.
p{N} It matches any string containing a sequence of N p's
p{2,3} It matches any string containing a sequence of 2/3 p's.
p$ It matches any string with p at the end of it.
^p It matches any string with p at the beginning of it.
91
p{2, } It matches any string containing sequence of at least 2
p‘s
Cont…
Examples:
Expression Description
[^a-zA-Z] It matches any string not containing
any of characters ranging from a through z
and A through Z.
p.p It matches any string containing p,
followed by any character, in turn
followed by another p.
^.{2}$ It matches any string containing
exactly two characters.
<b>(.*)</b> It matches any string enclosed within
<b> and </b>.
p(hp)* It matches any string containing a p
followed by zero or more instances of 92the
sequence hp.
Cont…
3) Predefined Character Ranges
Also known as character classes.
95
Cont…
PERL Style Regular Expressions:- similar to their POSIX
counterparts and used almost interchangeably
1) Metacharacters:- It is simply an alphabetical character preceded
by a backslash that acts to give the combination a special meaning.
Character Description
. a single character
\s a whitespace character (space, tab, newline)
\S non-whitespace character
\d a digit (0-9) and \D a non-digit
\w word character (a-z, A-Z, 0-9, _)
\W non-word character
[aeiou] matches a single character in the given set
[^aeiou] matches single character outside the given set96
(foo|bar|baz) matches any of the alternatives specified
Cont…
2) Modifiers
Several modifiers are available that can make your work with
regexps much easier, like case sensitivity, searching in multiple
lines etc.
Modifier Description
i Makes the match case insensitive
m Specifies that if the string has newline or carriage
return characters, the ^ and $ operators will now match
against a newline boundary, instead of a string
boundary
o Evaluates the expression only once
s Allows use of . to match a newline character
x Allows U 2 use whitespace in the expression for clarity
g Globally finds all matches 97
?>
Cont…
2) Defining Custom Error Handling Function:
You can write your own function to handling any error and PHP
provides you a framework to define error handling function.
This function must be able to handle a minimum of two parameters
(error level and error message) but can accept up to five parameters
(optionally: file, line-number, and the error context):
Syntax: error_function(error_level, error_message,
error_file, error_line, error_context);
Parameter Description
error_level – Specifies error report level for the user-defined error.
error_message – Specifies error message for the user-defined error
error_file – Specifies filename in which the error occurred
error_line - Specifies the line number in which the error occurred
100
error_context – Specifies array containing every variable and their values
in use when the error occurred
Cont…
Exceptions Handling:
Exceptions are important and provides a better control over error
handling.
1) Using Try --- Catch
Try - A function using an exception should be in a "try" block. If
the exception does not trigger, the code will continue as normal.
However if the exception triggers, an exception is "thrown".
Throw - This is how you trigger an exception. Each "throw" must
have at least one "catch".
Catch - - A "catch" block retrieves an exception and creates an
object containing the exception information.
When an exception is thrown, code following the statement will not
be executed, and PHP will attempt to find the first matching catch
block. If an exception is not caught, a PHP Fatal Error will101be
issued with an "Uncaught Exception ...
Cont…
Each try must have at least one corresponding catch block. Multiple
catch blocks can be used to catch different classes of exceptions.
Exceptions can be thrown (or re-thrown) within a catch block.
Example: <?php
try {
$error = 'Always throw this error';
throw new Exception($error);
// Code following an exception is not executed.
echo 'Never executed‘; }
catch (Exception $e) {
echo 'Caught exception: ', $e->getMessage(), "\n";
}
102
// Continue execution
echo 'Hello World‘; ?>
Cont…
In the above example $e->getMessage function is used to get error
message.
There are following functions which can be used from Exception
class.
getMessage() - message of exception
getCode() - code of exception
getFile() - source filename
getLine() - source line
getTrace() - n array of the backtrace()
getTraceAsString() - formated string of trace
103
Cont…
2) Creating Custom Exception Handler:
You can define your own custom exception handler.
quality in software
Cont…
Guidelines while coding in PHP:
Indenting and Line Length:
Use an indent of 4 spaces and don't use any tab because
different computers use different setting for tab. It is
recommended to keep lines at approximately 75-85 characters
long for better code readability.
Control Structures:
Control statements should have one space between the control
default action;
Cont…
Function Calls:
Functions should be called with no spaces between the function
name, the opening parenthesis, and the first parameter; spaces
between commas and each parameter, and no space between the
last parameter, the closing parenthesis, and the semicolon.
Here's an example:$var = foo($bar, $baz, $quux);
Function Definitions:
Function declarations follow the "BSD/Allman style":
Comments - Use only C++ and C comments that are (/* */) and (//)
PHP Code Tags :
Always use <?php ?> to delimit PHP code, not the <? ?>
shorthand.
This is required for PHP compliance and is also the most
107
portable way to include PHP code on differing operating
systems and setups.
Cont…
Variable Names:
Use all lower case letters
Use '_' as the word separator.
Global variables should be prepended with a 'g'.
Global constants should be all caps with '_' separators.
Static variables may be pre-pended with 's'.
Make Functions Reentrant: Functions should not keep static
variables that prevent a function from being reentrant.
Alignment of Declaration Blocks: Block of declarations should be
aligned.
One Statement Per Line -There should be only one statement per
line unless the statements are very closely related.
Short Methods or Functions - Methods should limit themselves108 to
a single page of code.
3. 18 Web Concepts
How PHP can provide dynamic content according to browser
type, randomly generated numbers or User Input and how the
client browser can be redirected?
1) Identifying Browser & Platform
PHP allows us an environment variables called
HTTP_USER_AGENT which identifies the user's browser
and operating system.
PHP provides a function getenv() to access the value of all the
environment variables.
The information contained in the HTTP_USER_AGENT
environment variable can be used to create dynamic content
appropriate to the browser. 109
Cont…
Example to demonstrates how you can identify a client browser
and operating system
<html><body>
<?php
$viewer = getenv( "HTTP_USER_AGENT" );
$browser = "An unidentified browser";
if( preg_match( "/MSIE/i", "$viewer" ) )
{
$browser = "Internet Explorer";
}
else if( preg_match( "/Netscape/i", "$viewer" ) )
{
$browser = "Netscape"; 110
}
Cont…
else if( preg_match( "/Mozilla/i", "$viewer" ) ) {
$browser = "Mozilla";
}
$platform = "An unidentified OS!";
if( preg_match( "/Windows/i", "$viewer" ) ) {
$platform = "Windows!";
}
else if ( preg_match( "/Linux/i", "$viewer" ) ) {
$platform = "Linux!";
}
echo("You are using $browser on $platform");
?>
</body> 111
</html>
Cont…
2) Display Images Randomly
The PHP rand() function is used to generate a random number
with-in a given range.
The random number generator should be seeded to prevent a
regular pattern of numbers being generated.
This is achieved using the srand() function that specifies the
seed number as its argument.
3) Using HTML Forms
any form element in an HTML page will automatically be
available to your PHP scripts.
The PHP default variable $_PHP_SELF is used for the PHP
script name and when you click "submit" button then same
PHP script will be called and will produce following result:
112
The method = "POST" is used to post user data to the server
script.
Cont…
Example for demonstrating how you can display different image
each time out of four images:
<html><body>
<?php
srand( microtime() * 1000000 ); $num = rand( 1, 4 );
switch( $num ) {
case 1: $image_file = "/home/images/alfa.jpg";
break;
case 2: $image_file = "/home/images/ferrari.jpg";
break;
}
echo "Random Image : <img src=$image_file />";
?>
113
</body>
</html>
Cont…
4) Browser Redirection
The PHP header() function supplies raw HTTP headers to the
browser and can be used to redirect it to another location.
The redirection script should be at the very top of the page to
prevent any other part of the page from loading.
The target is specified by the Location and the exit() function
can be used to halt parsing of rest of the code.
5) Displaying "File Download" Dialog Box
Sometime when a user will click a link and it will pop up a
"File Download" box to the user in stead of displaying actual
content and will be achieved through HTTP header.
The HTTP header will be different from the actual header
where we send Content-Type as text/html\n\n. In this case
content type will be application/octet-stream and actual file
114
117
118