2 PHP
2 PHP
2 PHP
Unit Two
The if, else if ...else and switch statements are used to take decision based on the different
condition.
You can use conditional statements in your code to make your decisions. PHP supports
following decision making statements:
The if Statement
Use the if statement to execute some code only if a specified condition is true.
Syntax
if (condition)
code to be executed if condition is true;
The following example will output "Have a nice weekend!" if the current day is Friday:
<?php
$d=date("D");
if ($d=="Fri") echo "Have a nice weekend!";
?>
Notice that there is no ..else.. in this syntax. The code is executed only if the specified condition
is true.
Use this statement, if you want to execute some code if a condition is true and another code if a
condition is false.
Syntax
if (condition)
code to be executed if condition is true;
else
code to be executed if condition is false;
Note: If more than one line should be executed if a condition is true/false, the lines should be
enclosed within curly braces.
Example:
The following example will output "Have a nice weekend!" if the current day is Friday,
otherwise it will output "Have a nice day!”
<?php
$d=date("D");
if ($d=="Fri")
echo "Have a nice weekend!";
else
echo "Have a nice day!";
?>
If you want to execute some code if one of the several conditions is true, then use the elseif
statement.
Syntax
if (condition)
code to be executed if condition is true;
else if(condition)
code to be executed if condition is true;
else
code to be executed if condition is false;
Example:
The following example will output "Have a nice weekend!" if the current day is Friday, and
"Have a nice Sunday!" if the current day is Sunday. Otherwise it will output "Have a nice day!"
<?php
$d=date("D");
if ($d=="Fri")
echo "Have a nice weekend!";
elseif ($d=="Sun")
echo "Have a nice Sunday!";
else
echo "Have a nice day!";
?>
If you want to select one of many blocks of code to be executed, use the Switch statement.
The switch statement is used to avoid long blocks of if..else if..else code.
Syntax:
switch (expression)
{
case label1:
code to be executed if expression = label1;
break;
case label2:
code to be executed if expression = label2;
Page 2 of 31 KIot, 2013
Chapter Two PHP Statements & Forms
break;
default:
code to be executed if expression is different from both label1 and label2; }
Example
The switch statement works in an unusual way. First it evaluates given expression then seeks a
label to match the resulting value. If a matching value is found, then the code associated with the
matching label will be executed. If none of the labels match, then the statement will execute any
specified default code.
<?php
$d=date("D");
switch ($d)
{
case "Mon":
echo "Today is Monday";
break;
case "Tue":
echo "Today is Tuesday";
break;
case "Wed":
echo "Today is Wednesday";
break;
case "Thu":
echo "Today is Thursday";
break;
case "Fri":
echo "Today is Friday";
break;
case "Sat":
echo "Today is Saturday";
break;
case "Sun":
echo "Today is Sunday";
break;
default:
echo "Wonder which day is this ?";
}
?>
Loops in PHP are used to execute the same block of code a specified number of times. PHP
supports following four loop types.
The for loop is used when you know in advance how many times the script should run.
Syntax
initialization: Mostly used to set a counter (but can be any code to be executed once at
the beginning of the loop)
condition: Evaluated for each loop iteration. If it evaluates to TRUE, the loop continues.
If it evaluates to FALSE, the loop ends.
increment: Mostly used to increment a counter (but can be any code to be executed at the
end of the loop)
Note: Each of the parameters above can be empty, or have multiple expressions (separated by
commas).
Example
1. The example below defines a loop that starts with i=1. The loop will continue to run as long as i is less than, or equal to
5. i will increase by 1 each time the loop runs:
<?php
for ($i=1; $i<=5; $i++)
{
echo "The number is " . $i . "<br />";
}
?>
2. The following example displays a product table
<html><body>
<?php
echo "<h1>Multiplication table</h1>";
echo "<table border=2 width=50%";
for ($i = 1; $i <= 5; $i++ ) { //this is the outer loop
echo "<tr>";
echo "<td>".$i."</td>";
for ( $j = 2; $j <= 5; $j++ ) { // inner loop
echo "<td>".$i * $j."</td>";
}
echo "</tr>";
}
echo "</table>";
?>
</body>
</html>
The while statement will execute a block of code if and as long as a test expression is true. If the
test expression is true then the code block will be executed. After the code has executed the test
expression will again be evaluated and the loop will continue until the test expression is found to
be false.
Syntax
while (condition)
{
code to be executed;
}
Example: The following example shows how to insert years from 1970-2015 in a form list box
and display the selected year upon submit.
<html><body>
<form action="" method="post">
Year:<select name="year">
<?php
$year=1970;
while($year<=2015)
{ echo "<option value=$year>$year</option>";
$year++;
}
echo "</select>";
?>
<br><input type="submit" value="Display"></form>
<?php
$year=$_POST['year'];
if($year!=null)
echo "Year:$year";
?>
</body></html>
The do...while statement will always execute the block of code once, it will then check the
condition, and repeat the loop while the condition is true.
Syntax
do
{
code to be executed;
}
while (condition);
Example
The example below defines a loop that starts with i=1. It will then increment i with 1, and write
some output. Then the condition is checked, and the loop will continue to run as long as i is less
than, or equal to 5:
<html><body>
<?php
$i=1;
echo “The number is:”;
do
{
$i++;
echo "$i ";
}
while ($i<=5);
?>
</body></html>
The foreach statement is used to loop through arrays. For each pass the value of the current array
element is assigned to $value and the array pointer is moved by one and in the next pass next
element will be processed.
Syntax
foreach (array as value)
{
code to be executed;
}
Example
Try out the following example to list out the values of an array.
<?php
$array = array( 1, 2, 3, 4, 5);
echo "Values of the array:”;
foreach( $array as $value )
{
echo “$value ";
}
?>
This will produce the following result:
Example:
<?php
$i = 0;
while( $i < 10)
{
$i++;
if( $i == 3 ) break;
}
echo ("Loop stopped at i = $i" );
?>
The PHP continue keyword is used to halt the current iteration of a loop but it does not terminate
the loop. Just like the break statement the continue statement is situated inside the statement
block containing the code that the loop executes, preceded by a conditional test. For the pass
encountering continue statement, rest of the loop code is skipped and next pass starts.
Example
In the following example loop prints the value of array but for which condition becomes true it
just skip the code and next value is printed.
<?php
$array = array( 1, 2, 3, 4, 5);
echo “Values of the array:”;
foreach( $array as $value )
{
if( $value == 3 )continue;
echo "$value ";
}
?>
This will produce the following result:
Values of the array:1 2 4 5
2.3. Arrays
A variable is a storage area holding a number or text. The problem is, a variable will hold only
one value.
An array is a special variable that stores one or more similar type of values in a single variable.
For example if you want to store 100 numbers then instead of defining 100 variables it’s easy to
define an array of 100 length.
An array can hold all your variable values under a single name. And you can access the values
by referring to the array name. Each element in the array has its own index so that it can be
easily accessed.
Numeric array - An array with a numeric index. Values are stored and accessed in linear
fashion
Associative array - An array where each ID key is associated with a value
Multidimensional array - An array containing one or more arrays and values are
accessed using multiple indices
Numeric Array
These arrays can store numbers, strings and any object but their index will be represented by
numbers. By default, the array index starts from zero.
Example
The following example demonstrates how to create and access numeric arrays. Here we have
used array() function to create array.
<?php
/* First method to create array. */
$numbers = array( 1, 2, 3, 4, 5);
echo "Value of the array:”;
foreach( $numbers as $value )
{
echo "$value ";
}
/* Second method to create array. */
$numbers[0] = "one";
$numbers[1] = "two";
$numbers[2] = "three";
$numbers[3] = "four";
$numbers[4] = "five";
echo "Value of the array:”;
Page 8 of 31 KIot, 2013
Chapter Two PHP Statements & Forms
Associative Arrays
The associative arrays are very similar to numeric arrays in terms of functionality but they are
different in terms of their index. When storing data about specific named values, a numerical
array is not always the best way to do it. Associative array will have their index as string so that
you can establish a strong association between key and values.
Example 1
<?php
$credit_hour = array("AIP"=>3, "AP"=>3, "DCN"=>4, "CMT"=>4, "EDP"=>4);
$grade = array("AIP"=>'A', "AP"=>'B', "DCN"=>'C', "CMT"=>'A', "EDP"=>'C');
$grade_point= array("AIP"=>12, "AP"=>9, "DCN"=>8, "CMT"=>16, "EDP"=>8);
foreach($credit_hour as $value)
$total_credit_hour+=$value;
foreach($grade_point as $value)
$total_grade_point+=$value;
$semester_gpa=number_format(($total_grade_point/$total_credit_hour),2);
echo "GPA:".$semester_gpa;
?>
This will produce the following result:
GPA: 2.94
NOTE: Don't keep associative array inside double quote while printing, otherwise it would not
return any value.
Multidimensional Arrays
A multi-dimensional array each element in the main array can also be an array. And each
element in the sub-array can be an array, and so on. Values in the multi-dimensional array are
accessed using multiple indexes.
Example:
<?php
$grade = array("Abebe"=>array("AIP"=>'A',"AP"=>'B'),"Ermias"=>array("AIP"=>'B',
"AP"=>'C'));
foreach($grade['Abebe'] as $key=>$value)
echo "<br>Abebe scored:".$value." in ".$key;
foreach($grade['Ermias'] as $key=>$value)
echo "<br>Ermias scored:".$value." in ".$key;
?>
This will produce the following result:
$grade['Abebe']['AP']="B";
$grade[‘Ermias’]['AIP']="B";
$grade[‘Ermias’]['AP']="C";
foreach($grade['Abebe'] as $key=>$value)
echo "<br>Abebe scored:".$value." in ".$key;
foreach($grade['Ermias'] as $key=>$value)
echo "<br>Ermias scored:".$value." in ".$key;”\
?>
This will produce the same output as the above example.
PHP comes with four functions that allow us to add or remove elements from the beginning or
end of an array: the array_unshift() function adds an element to the beginning of an array; the
array_shift() function removes the first element of an array; the array_push() function adds an
element to the end of an array; and the array_pop() function removes the last element of an
array. The following listing illustrates them all in action:
<?php
// define array
$movies = array('The Lion King', 'Cars', 'A Bug\'s Life');
// remove element from beginning of array
array_shift($movies);
// remove element from end of array
array_pop($movies);
// add element to end of array
array_push($movies, 'Ratatouille');
// add element to beginning of array
array_unshift($movies, 'The Incredibles');
// print array
// output: ('The Incredibles', 'Cars', 'Ratatouille')
print_r($movies);
?>
Notethat:- The array_unshift(), array_shift(), array_push(), and array_pop() functions should be
used only with numerically indexed arrays and not with associative arrays. Each of these
functions automatically re-indexes the array to account for the value(s).
Sorting Arrays
PHP comes with a number of built-in functions designed for sorting array elements in
different ways. The first of these is the sort() function, which lets to sort numerically indexed
arrays alphabetically or numerically, from lowest to highest value.
Some Sorting Functions of PHP which has different sorting orders are:-
PHP functions are similar to other programming languages. A function is a piece of code which
takes one or more input in the form of parameter and does some processing and returns a value.
Functions MUST be defined before they called. Functions can only be executed if they
are called. Function headers are of the format:- function functionName($arg_1, $arg_2,
…, $arg_n)
Unlike variables, function names are not case sensitive (foo(…) == Foo(…) == FoO(…))
Function statements do the actual work of the function and must be contained within
the function braces
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. The following example shows both the cases.
<html><body>
<?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 />";
?>
</body></html>
iv. 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. It is
possible to return more than one value from a function using return array(1,2,3,4).
The following example takes two integer parameters and adds them together and then returns
their sum to the calling program. Note that return keyword is used to return a value from a
function.
<html><body>
<?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>
We can return multiple values from a function, by placing them all in an array and returning the
array. The next example illustrates, by accepting a sentence and returning the individual words,
reversed, to the caller as an array:
<?php
function add_sub($num1,$num2){
$add=$num1+$num2;
$sub=$num1-$num2;
return array($add,$sub);
}
$result_array=add_sub(15,20);
echo "Add:".$result_array[0]."<br>";
echo "Sub:".$result_array[1]."<br>";
//you can use list function to assign the returned value to variables
list($add_result,$sub_result)=add_sub(30,20);
Page 13 of 31 KIot, 2013
Chapter Two PHP Statements & Forms
echo "Add:".$add_result."<br>";
echo "Sub:".$sub_result;
?>
v. Setting Default Values for Function Parameters:
We can set a parameter to have a default value if the function's caller doesn't pass it.
<?php
function studinfo($department="IT",$year="3rd"){
return "You are $year year $department student<br>";
}
echo studinfo();
echo studinfo("Software Engineering","1st");
echo studinfo("Electrical",Null);
echo studinfo("2nd");
?>
Output
You are 3rd year IT student
You are 1st year Software Engineering student
You are year Electrical student
You are 3rd year 2nd student
vi. Dynamic Function Calls:
It is possible to assign function names as strings to variables and then treat these variables
exactly as the function name itself. Following example depicts this behavior. From the following
code, Hello will be displayed.
<html><body>
<?php
function sayHello(){
echo "Hello<br />";}
$function_holder = "sayHello";
$function_holder();
?>
</body></html>
vii. Using Recursive Function
Another, slightly more complex idea involving functions is recursion. A recursive function is a
function that calls itself repeatedly until a condition is satisfied. Such a function is typically used
to solve complex, iterative calculations, or to process deeply nested structures.
<?php
function printValues($arr) {
global $count;
global $out;
if (!is_array($arr)) {
die('ERROR: Input is not an array');
}
foreach ($arr as $a) {
if (is_array($a)) {
printValues($a);
} else {
$out[] = $a;
$count++;
}
}
return array('total' => $count, 'values' => $out);
}
$data = array(
'o' => array(
'orange',
'owl',
'one'),
't' => array(
'tea',
'ten',
'tag',
'twentythree' => array(
array('twenty', 'three'),
array('vingt', 'trois', array(
'red' => 'baron',
'blue' => 'blood'
)))));
// count and print values in nested array
$ret = printValues($data);
echo $ret['total'] . ' value(s) found: ';
echo "<br/>";
echo implode(', ', $ret['values']);
?>
Output:
12 value(s) found:
orange, owl, one, tea, ten, tag, twenty, three, vingt, trois, baron, blood
o Using die() function:: - While writing PHP program, we should check all possible
error condition before going ahead and take appropriate action when required.
<?php
if(!file_exists("/tmp/test.txt"))
{
die("File not found");
}
else
{
$file=fopen("/tmp/test.txt","r");
print "Opend file sucessfully";
}
// Test of the code here.
?>
Using above technique, we can stop a program whenever errors occur and display more
meaningful and user friendly message.
Parameter Description
error_level Required - Specifies the error report level for the user-defined error. Must
be a value number.
error_messag Required - Specifies the error message for the user-defined error
e
error_line Optional - Specifies the line number in which the error occurred
error_context Optional - Specifies an array containing every variable and their values in
use when the error occurred
The following example shows how we could define error handling functions
<?php
function handleError($errno, $errstr,$error_file,$error_line)
{
echo "<b>Error:</b> [$errno] $errstr - $error_file:$error_line";
echo "<br />";
echo "Terminating PHP Script";
die();
}
?>
Once you define your custom error handler you need to set it using PHP built-in library
set_error_handler function. Now let’s examine our example by calling a function which does
not exist.
<?php
error_reporting( E_ERROR );
One of the most powerful features of PHP is the way it handles HTML forms. The basic concept
that is important to understand is that any form element will automatically be available to your
PHP scripts.
The form variables are available to PHP in the page to which they have been submitted. The
variables are available in three superglobal arrays created by PHP called $_POST, $_GET and
$_REQUEST.
The above code’s action attribute value can be represented as the filename itself like:-
<form action=”info.php” method=”Get”>
The POST method transfers information via HTTPs headers. The information is encoded as
described in case of GET method and put into a header called QUERY_STRING.
The POST method does not have any restriction on data size to be sent.
Relatively secured and can be used in large data requesting and responding
The POST method can be used to send ASCII as well as binary data.
The data sent by POST method goes through HTTP header so it is secured enough on
HTTP protocol. The PHP provides $_POST associative array to access all the
information sent using POST method.
Example: - Take the above example and change the value of method attribute in the form from
GET to POST and the variable from $_GET to $_POST.
The PHP $_REQUEST variable contains the contents of $_GET, $_POST, and
$_COOKIE variables
This variable can be used to get the result from form data sent with both the GET and
POST methods.
<html><body>
<form action="" method="post">
Username:<input type="text" name="username"><br>
Password:<input type="password" name="password"><br>
<input type="submit" value="Login">
</form>
</body>
</html>
<?php
$una="abc";
$pwd="abc1234";
$username=$_REQUEST['username'];
$password=$_REQUEST['password'];
if($username==$una&&$password==$pwd)
header("location:welcome.php");
else
echo "Please enter valid username/password";
?>
Save the above file with a filename login.php, run it and see the output.
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: header as the argument to the header () function. After
calling this function the exit () function can be used to halt parsing of rest of the code.
Form Validation
User input should be validated on the browser whenever possible (by client scripts). Browser
validation is faster and reduces the server load.
You should consider server validation if the user input will be inserted into a database. A good
way to validate a form on the server is to post the form to itself, instead of jumping to a different
page. The user will then get the error messages on the same page as the form. This makes it
easier to discover the error.
Common Validations
Presence Validation
String Length Validation
Type Validation
Inclusion in set Validation
Uniqueness Validation
Page 19 of 31 KIot, 2013
Chapter Two PHP Statements & Forms
Format Validation
if(!preg_match("/PHP/","PHP is SSS"))
die("match not found");
else
echo "Match Found!";
Digits 0-9 only: This uses to check whether an input is digit/ number or not. The
following is a syntax to check if $age is a number or not. If not number, it display
“Please enter numbers only for Age”
if (!preg_match("/^[.0-9]*$/",$value))
die("Please enter numbers only for Age");
or
$age= htmlspecialchars($_POST['age']);
if (!preg_match("/\D/",$age))
die("Please enter numbers only for Age");
Letters a-z and A-Z only
if (!preg_match("/^[a-zA-Z ]*$/",$value)) {
die("Only letters and white space allowed");
Validate e-mail address: Used to check an email is valid, i.e to have valid forms.
There is a simple way to check if data entered into input field named "email" is an
e-mail address without any unnecessary complications and fancy regular
expressions.
if (!filter_var($value, FILTER_VALIDATE_EMAIL))
die("Invalid email format");
Or
if(!preg_match("/([\w\-]+\@[\w\-]+\.[\w\-]+)/",$value))
die("Invalid email format");
URL Address: If there is an input field named "website" we can check for a valid
URL address like this
if (!preg_match("/\b(?:(?:https?|ftp):\/\/|www\.)[-a-z0-9+&@#\/%?
=~_|!:,.;]*[-a-z0-9+&@#\/%=~_|]/i",$value)) {
die("Invalid URL");
Example: Using form validation. The validation rules here are:
Display “Welcome! Please fill the following fields if you wanna sign up!” message
while the page is opened for the first time.
Display “Please fill all the required fields!” message if all of the fields are empty upon
submission.
Display “First Name can contain only characters!” message if the user enters characters
other than a-z or A-Z in FirstName field.
Display “Last Name can contain only characters!” message if the user enters characters
other than a-z or A-Z in LastName field.
Display “Age can only be number!” message if the user enters characters other than 0-9
in FirstName field.
Display “Invalid Email!” message if the user enters an email which does not include @
and . symbols in it.
Display “Username already exist!” message if the user enter either of abc,12, xyz
usernames
Display “Password must be above 6 characters!” message if the user enters a password
which consists 6 or less characters.
Display “Invalid URL!” message if the user enters a website which does not contain
http/s,ftp,www,.domainname.
Otherwise display all the values submitted from the form.
Formvalidation.php
<html>
<head><link rel="stylesheet" type="text/css" href="formstyle.css"></head>
<body>
<div id="xx"><div id="xxx"><h1>User SignUp Form</h1></div>
<hr> <div id="xxx">
<form action="" method="post">
FirstName:<input type="text" name="fname"><font>*</font><br>
LastName:<input type="text" name="lname"><font>*</font><br>
Sex:<select name="sex"><option value="" selected>Choose Gender</option><option
value="M">Male</option><option value="F">Female</option></select><font>*</font></br>
Age:<input type="text" name="age"><font>*</font><br>
Email:<input type="text" name="email"><font>*</font><br>
Username:<input type="text" name="username"><font>*</font><br>
Password:<input type="Password" name="password"><font>*</font><br>
Website(if any):<input type="text" name="website"><br>
<input type="submit" name="signup" value="SignUp"><input type="reset" value="Reset">
</form></div></div>
<?php
echo "<div id=xr><div id=xxx>";
if(isset($_POST['signup']))
{
if(!empty($_POST['fname'])&&!empty($_POST['lname'])&&!empty($_POST['sex'])&&!
empty($_POST['age'])&&!empty($_POST['email'])&&!empty($_POST['username'])&&!
empty($_POST['password']))
{
$fname=$_POST['fname'];
$lname=$_POST['lname'];
$sex=$_POST['sex'];
$age=$_POST['age'];
$email=$_POST['email'];
$usernames=array("abc","123","xyz");
$gender=array("M","F");
$username=$_POST['username'];
$password=$_POST['password'];
$website=$_POST['website'];
$c=0; $minchar=6;
if(!preg_match("/^[a-zA-Z ]*$/",$fname)) {
echo ("First Name can contain only characters<br>");
$c++;
}
if(!preg_match("/^[a-zA-Z ]*$/",$lname)) {
You can include the content of a PHP file into another PHP file before the server executes it.
There are two PHP functions which can be used to include one PHP file into another PHP file.
include() Function
require() Function
This is a strong point of PHP which helps in creating functions, headers, footers, or elements that
can be reused on multiple pages. This will help developers to make it easy to change the layout
of complete website with minimal effort. If there is any change required then instead of changing
thousand of files just change included file.
The include() function takes all the text in a specified file and copies it into the file that uses the
include function. If there is any problem in loading a file then the include () function generates a
warning but the script will continue execution.
Assume you want to create a common menu for your website. Then create a file menu.php with
the following content.
|<a href="index.php">Home</a>||
<a href="feedback.php">Feedback</a>||
<a href="login.php">Login</a>|
Now create as many pages as you like and include this file to create header. For example now
your test.php file can have following content.
<html>
<body>
<?php include("menu.php"); ?>
<p>This is an example to show how to include PHP file!</p>
</body>
</html>
This will produce the following result:
|Home||Feedback||Login|
This is an example to show how to include PHP file.
You can include menu.php file in as many as files you like!
The require() function takes all the text in a specified file and copies it into the file that uses the
require function. If there is any problem in loading a file then the require() function generates a
fatal error and halt the execution of the script.
So there is no difference in require() and include() except they handle error conditions. It is
recommended to use the require() function instead of include(), because scripts should not
continue executing if files are missing or misnamed.
You can try using above example with require() function and it will generate same result. But if
you will try following two examples where file does not exist then you will get different results.
<html> <body>
<?php include("xxmenu.php"); ?>
<p>This is an example to show how to include wrong PHP file!</p>
</body> </html>
This will produce the following result:
This is an example to show how to include wrong PHP file!
Now lets try same example with require() function.
<html> <body>
<?php require("xxmenu.php"); ?>
<p>This is an example to show how to include wrong PHP file!</p>
</body> </html>
This time file execution halts and nothing is displayed.
NOTE: You may get plain warning messages or fatal error messages or nothing at all. This
depends on your PHP Server configuration.
A client can visit and load a website several times. If so, there should be certain mechanism to
remember the previous instances of it being requested by a client. This leads to persistency of
files or data.
As discussed in IP-I, http is a stateless protocol. It remembers nothing about previous transfers.
2.6.1 Cookies
A cookie is a packet of information sent from the server to client, and then sent back to the
server each time. Or cookies are text files stored on the client computer and they are kept of use
tracking purpose. PHP transparently supports HTTP cookies.
Server script sends a set of cookies to the browser. For example name, age, or
identification number etc.
Browser stores this information on local machine for future use.
When next time browser sends any request to web server then it sends those cookies
information to the server and server uses that information to identify the user.
Cookies are usually set in an HTTP header (although JavaScript can also set a cookie directly on
a browser). A PHP script that sets a cookie might send headers that look something like this:
HTTP/1.1 200 OK
Date: Fri, 04 Feb 2000 21:03:38 GMT
Server: Apache/1.3.9 (UNIX) PHP/4.0b3
Set-Cookie: name=xyz; expires=Friday, 04-Feb-07 22:03:38 GMT;
path=/; domain=tutorialspoint.com
Connection: close
Content-Type: text/html
As you can see, the Set-Cookie header contains a name value pair, a GMT date, a path and a
domain. The name and value will be URL encoded. The expires field is an instruction to the
browser to "forget" the cookie after the given time and date.
If the browser is configured to store cookies, it will then keep this information 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. The browser's headers might look something like this:
GET / HTTP/1.0
Connection: Keep-Alive
User-Agent: Mozilla/4.6 (X11; I; Linux 2.2.6-15apmac ppc)
Host: zink.demon.co.uk:1126
Accept: image/gif, */*
Accept-Encoding: gzip
Accept-Language: en
Accept-Charset: iso-8859-1,*,utf-8
Cookie: name=xyz
A PHP script will then have access to the cookie in the environmental variables $_COOKIE or
$HTTP_COOKIE_VARS[] which holds all cookie names and values. Above cookie can be
accessed using $HTTP_COOKIE_VARS["name"].
PHP provided setcookie() function to set a cookie. This function requires up to six arguments
and should be called before <html> tag. For each cookie this function has to be called separately.
setcookie(name, value, expire, path, domain, security);
Here is the detail of all the arguments:
Name - This sets the name of the cookie and is stored in an environment variable called
HTTP_COOKIE_VARS. This variable is used while accessing cookies.
Value -This sets the value of the named variable and is the content that you actually want
to store.
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 automatically expire when the Web Browser is closed.
Path -This specifies the directories for which the cookie is valid. A single forward slash
character permits the cookie to be valid for all directories.
Domain - This can be used to specify the domain name in very large domains and must
contain at least two periods to be valid. All cookies are only valid for the host and domain
which created them.
Security - This can be set to 1 to specify that the cookie should only be sent by secure
transmission using HTTPS otherwise set to 0 which mean cookie can be sent by regular
HTTP.
The following example will create two cookies name and age. These cookies will expire after an
hour.
<?php
PHP provides many ways to access cookies. The simplest way is to use either $_COOKIE or
$HTTP_COOKIE_VARS variables. Following example will access all the cookies set in above
example.
Officially, to delete a cookie you should call setcookie() with the name argument only but this
does not always work well, however, and should not be relied on. It is safest to set the cookie
with a date that has already expired:
<?php
setcookie( "name", "", time()- 60, "/","", 0);
setcookie( "age", "", time()- 60, "/","", 0);
?>
2.6.2. Sessions
An alternative way to make data accessible across the various pages of an entire website is to use
a PHP Session.
A session creates a file in a temporary directory on the server where registered session variables
and their values are stored. This data will be available to all pages on the site during that visit.
The location of the temporary file is determined by a setting in the php.ini file called
session.save_path. Before using any session variable make sure you have setup this path.
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 temporary directory and
bears the name of the unique identifier prefixed by sess_ ie
sess_3c7foj34c3jj973hjkop2fc937e3443.
When a PHP script wants to retrieve the value from a session variable, PHP automatically gets
the unique session identifier string from the PHPSESSID cookie and then looks in its temporary
directory for the file bearing that name and a validation can be done by comparing both values.
A session ends when the user loses the browser or after leaving the site, the server will terminate
the session after a predetermined period of time, commonly 30 minutes duration.
A PHP session is easily started by making a call to the session_start() function. This function
first checks if a session is already started and if none is started then it starts one. It is
recommended to put the call to session_start() at the beginning of the page.
Session variables are stored in associative array called $_SESSION[]. These variables can be
accessed during lifetime of a session.
The following example starts a session and then registers a variable called counter that is
incremented each time the page is visited during the session.
Make use of isset() function to check if session variable is already set or not.
Put this code in a test.php file and load this file many times to see the result:
<?php
session_start();
if( isset( $_SESSION['counter'] ) )
{
$_SESSION['counter'] += 1;
}
else
{
$_SESSION['counter'] = 1;
}
$msg = "You have visited this page ". $_SESSION['counter'];
$msg .= "in this session.";
?>
<html><head> <title>Setting up a PHP session</title> </head>
<body>
<?php echo ( $msg ); ?>
</body>
</html>
A PHP session can be destroyed by session_destroy() function. This function does not need any
argument and a single call can destroy all the session variables. If you want to destroy a single
session variable then you can use unset () function to unset a session variable.
?>