The protocol used to run web pages is the HTTP protocol. This is a stateless protocol. That is, the web server does not track the behavior of individual users. Each ask for comes to the web server are treated as sole. Hence it is not possible to decide which user made a request at what time. To overcome this “stateless” nature of the web server, we use sessions and cookies to uphold the state of the site.
Sessions
Sessions are used to path the activities of a particular user. If a user visits our site, then the server generates an only one of its kind id known as session id. Using this number we can also recreate the before created session environment. Using session variables we can store either textual or numeric in sequence and these information can be easily accessed from side to side the super global array $_SESSION. Some of the common php session handling functions is listed below.
session_start()
This function is used to start a session in php. If we use cookies to store session data, then we must call the session_start() function before any output is produce. In such cases the session_start() function must be the first line in our script. This line must be there for all pages in which we use $_SESSION variables to re make the preceding session surroundings
<? Php
//Used to start the session
session_start();
//registering a session variable
$_SESSION ['state'] =”Delhi”;
?>
Save this page as first.php and create one more page named second.php and save the following data
<? Php
//Used to restart the session
session_start();
// now we using the session stored in the previous page
echo “You are from “.$_SESSION['state'];
?>
session_destroy()
This function is used to destroy the current session. This function is mainly seen in logout module of a project. Before using the session_destroy() function we must use session_start() to recreate the environment.
<?php
//Used to restart the session
session_start();
//destroy the session
session_destroy();
//testing the session
echo “You are from “.$_SESSION['state'];
?>
Cookies
Cookies are used as an alternate of session. In cookies the information about the client state is kept at a file inside the client system. Cookies can be read only by the site which creates them. Maximum size of a cookie is limited to 4-6KB. If the user turn off cookie support in their browser, then the cookie does not saved. So using cookies for important user tracking is risky.
setcookie()
The setcookie() function is used for saving the cookies in client system. The first parameter of this function indicates the Name of the cookie and second parameter indicates the Value stored in the cookie. The date and time at which the cookie expired is set in Expires limit. Path specifies the index on the domain from which cookie data can be accessed>Domain specifies the domain for the cookie. The secure attributes is a Boolean flag indication that the cookie should be transmitted over a secure link https
<? Php
// set a cookie named user with value Mike and expires after 1 day
$flag = setcookie(‘users’,'Mike’,time()+(3600 * 24),’/');
# time() will returns the current unix time stamp
if($flag)
echo “Cookie is created”;
else
echo “Cookie is not created”;
?>
Accessing value from a cookie
To access the value from a cookie we use the super global variable $_COOKIE.
<?php
if(isset($_COOKIE['users']))
echo “Cookie value is “.$_COOKIE['users'];
?>
setrawcookie()
This function is also used for creating a cookie. This method is similar to set cookie method except that the values saved in the cookie is not url encoded automatically when sending to the browser
Deleting a cookie
For deleting a cookie we used the same function setcookie() with same name. But the expires parameter should be something from the past.
<?php
// now the cookie is deleted…Note the expire field
setcookie(‘user’,'Mike’,time()-(3600 * 24),’/');
?>
The HTTP functions let you influence information sent to the browser by the Web server, before any other output has been sent.
The index functions are part of the PHP core. There is no installation needed to employ these functions.
PHP: indicates the earliest version of PHP that ropes the function.
| Function | Description | PHP version |
|---|---|---|
| header() | Sends a raw HTTP header to a client | 3 |
| headers_list() | Returns a list of response headers sent (or ready to send) |
5 |
| headers_sent() | Checks if / where the HTTP headers have been sent | 3 |
| setcookie() | Sends an HTTP cookie to a client | 3 |
| setrawcookie() | Sends an HTTP cookie without URL encoding the cookie value |
5 |
Setting and reading cookies in PHP is a part of–dare we say it?–cake. We don’t want to get into all the misinformation about cookies, but they’re important and useful. Sometimes they’re the right tool for the work.
create and modify a cookie In PHP
To create and modify a cookie, use the PHP function setcookie(). setcookie() takes up to six arguments, depending upon how much control you want over the cookie and who can read its value.
The best way of setting a cookie is like this:
setcookie(‘name’, ‘xxx’);
Then, for every further page on your site viewed by this browser (without the user quitting) you’ll have the value of ‘xxx’ stored in the variable $name for easy right to use in PHP. This type of cookie is known as a session cookie, since it lasts for the length of a user’s session.
If you want the cookie to persevere after the person exits his or her browser, you must pass setcookie() through a third parameter, the date you want the cookie to expire. Since PHP’s background springs fully formed from the head of Unix, you correspond to this time as the number of seconds since March 23, 1985. If you’re a Unix programmer, this makes total sense. But, if you’re from a Windows or a Macintosh background, you’re just trembling your head wondering if you’ll ever understand those wacky Unix folk.
PHP has a very nice function, mktime(). You pass mktime() (in this order) the hour, minute, second, month, day, and year that you want to represent, and mktime() returns to you the number of seconds since March 1, 1985. So, if you want to simulate a ZZZ meltdown:
<?php
$ZZZ = mktime(0,0,0,1,1,2000);
setcookie(‘name’, ‘xxx’, $ZZZ);
?>
your cookie will end with the millennium.
If you want to update a cookie to store a newer value, you can simply overwrite its value. So, even if you’ve previously sent the cookie above on an earlier page, it’s perfectly legal to go ahead and change your name to “akki.”
<?php
$ZZZ = mktime(0,0,0,1,1,2000);
setcookie(‘name’, ‘akki’, $ZZZ);
?>
Note that doing this doesn’t alter the value of the variable $name. It’s set when the page is loaded. If you want to make sure these two are always in sync, you can code like this:
<?php
$name = ‘Akki’;
$ZZZ = mktime(0,0,0,1,1,2000);
setcookie(‘name’, $name, $ZZZ);
?>
The next two parameters for setcookie() let you control the path and the domain of who can read your cookie. By default, only pages equivalent to or lower down in the ladder on the same server that sends the cookie can read its value. That’s for security’s sake. However, if you had an account that’s sometimes “www.any.com” but also “other.any.com,” and your account lets you serve pages from ~/myhome, you should modify setcookie() as such:
<?php
setcookie(‘name’, ‘akki’, $ZZZ, ‘~/myhome’, ‘.any.com’);
?>
The last parameter to setcookie(), which we’ve never used, teach that the cookie be sent only to a Web server that’s running a secure connection such as SSL. For this to occur, set the sixth value to 1.
Delete Cookie
Deleting a cookie is simple, simply pass setcookie() the name of your cookie and PHP will arrange for it to be deleted.
<?php setcookie(‘name’); ?>
There’s one last important item to cite about using cookies. Because of the way cookies work within HTTP, it’s important that you send all cookies before you print any text. If you don’t, PHP will give you a warning and your cookies will not be sent. So, this is OK:
<?php
setcookie(‘name’, ‘akki’);
echo “Good Morning!”;
?>
But this is not:
<?php
echo “Good Morning!”;
setcookie(‘name’, ‘akki’);
?>
Looping statements in PHP are used to carry out the same block of code a specified number of times.
Very often when you write code, you want the same block of code to run a number of times. You can use looping statements in your code to perform this.
In PHP There are four looping statements:
(1) do…while – loops through a block of code once, and then repeats the loop as long as a special condition is true
(2) for – loops through a block of code a specified number of times
(3) while – loops through a block of code if and as long as a specified condition is true
(4) for each – loops through a block of code for each element in an array
(1) The do…while Statement
The do…while statement will execute a block of code at least once – it then will repeat the loop as long as a condition is true.
Syntax
do
{
Code to be execute;
}
while (condition);
Example
The following example will increment the value of i at least once, and it will continue incrementing the variable i as long as it has a value of less than 5:
<html>
<body>
<?php
$j=0;
do
{
$j++;
echo “The figure is ” . $j . “<br />”;
}
while ($j<5);
?>
</body></html>
(2)The for Statement
The for statement is used when you know how many times you want to execute a statement or a list of statements.
Syntax
for (initialization; condition; increment)
{
code to be executed;
}
Message: The for statement has three parameters. The first parameter initializes variables, the second parameter holds the condition, and the third parameter contains the increments required to implement the loop. If more than one variable is included in the initialization or the increment parameter, they should be separated by commas. The condition must evaluate to true or false.
Example
The following example prints the text “Welcome” five times:
<html>
<body>
<?php
for ($j=1; $j<=5; $j++)
{
echo “Welcome<br />”;
}
?>
</body>
</html>
(3)The while Statement
The while statement will execute a block of code if and as long as a condition is true.
Syntax
while (condition)
Code to be executed;
Example
The following example demonstrates a loop that will continue to run as long as the variable i is less than, or equal to 5. i will increase by 1 each time the loop runs:
<html>
<body>
<?php
$j=1;
while($J<=5)
{
echo “The figure is ” . $j . “<br />”;
$j++;
}
?>
</body>
</html>
(4)The for each Statement
The for each statement is used to loop through arrays.
For every loop, the value of the current array element is assigned to $value (and the array pointer is moved by one) – so on the next loop, you’ll be looking at the next element.
Syntax
For each (array as value)
{
Code to be executed;
}
Example
The following example demonstrates a loop that will print the values of the given array:
<html>
<body>
<?php
$arr=array(“one”, “two”, “three”);
foreach ($arr as $value)
{
echo “Value: ” . $value . “<br />”;
}
?>
</body>
</html>
An array can store one or more values in a single variable name.
What is an array?
When working with PHP, earlier or later, you might want to create many similar variables.
In place of having many similar variables, you can store the data as elements in an array.
Each element in the array has its own ID so that it can be easily accessed.
There are three different types of arrays:
1 Numeric array – An array with a numeric ID key
2 Multidimensional arrays – An array containing one or more arrays
3 Associative arrays – An array where each ID key is associated with a value
(1) Numeric Arrays
A numeric array stores each part with a numeric ID key.
There are different ways to create a numeric array.
Example
In this example the ID key is automatically assigned:
$names = array(“Akki”,”Jimmi”,”Joy”);
In this example we assign the ID key manually:
$names[0] = “Akki”;
$names[1] = “Jimmi”;
$names[2] = “Joy”;
The ID keys can be used in a script:
<?php
$names[0] = “Akki”;
$names[1] = “Jimmi”;
$names[2] = “Joy”;
echo $names[1] . ” and ” . $names[2] .
” are “. $names[0] . “’s partner”;
?>
The code above will output:
Jimmi and Joy are Akki’s partner
(2)Multidimensional Arrays
In a multidimensional 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.
Example
In this example we create a multidimensional array, with automatically assigned ID keys:
$families = array
(“Griffin”=>array
( “Akki”,”Pats”, “Maks”),
“Jimmi”=>array
(“Glenn” ),
“Brown”=>array
(“Cleveland”, “Loretta”,”Junior”));
The array above would look like this if written to the output:
Array
([Griffin] => Array
([0] => Akki
[1] => Pats
[2] => Maks )
[Jimmi] => Array
( [0] => Glenn )
[Brown] => Array
( [0] => Cleveland
[1] => Loretta
[2] => Junior))
3 Associative Arrays
An associative array, each ID key is associated with a value.
When storing data about specific named values, a numerical array is not always the best way to do it.
With associative arrays we can use the values as keys and assign values to them.
Example
In this example we use an array to assign ages to the different persons:
$ages = array(“Akki”=>21, “Jimmi”=>18, “Joy”=>20);
This example is the same as example 1, but shows a different way of creating the array:
$ages['Akki'] = “21″;
$ages['Jimmi'] = “18″;
$ages['Joy'] = “20″;
The ID keys can be used in a script:
<?php
$ages['Akki'] = “21″;
$ages['Jimmi'] = “18″;
$ages['Joy'] = “20″;
echo “Akki is ” . $ages['Akki'] . ” years old.”;
?>
The code above will output:
Akki is 21 years old.