You are on page 1of 8

1

UNIT 5
State Management

What is cookie
A cookie is a small bit of information store on client computer
(nearly 4KB) . They are typically used to keeping track of information such as
username that the site can retrieve to personalize the page when user visit the
website next time.
PHP transparently supports HTTP cookies. Cookie is created at server side and
saved to client browser. Each time when client sends request to the server, cookie
is embedded with request. Such way, cookie can be received at the server side.
There are three steps involved in identifying returning users −
a)Server script sends a set of cookies to the browser. For example name, age, or
identification number etc.
b)Browser stores this information on local machine for future use.
c)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.
The Anatomy of a Cookie
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
Why and when to use Cookies?
Http is a stateless protocol; cookies allow us to track the state of the application
using small files stored on the user’s computer.
The path were the cookies are stored depends on the browser.
Internet Explorer usually stores them in Temporal Internet Files folder.
Personalizing the user experience – this is achieved by allowing users to select
their preferences.
The page requested that follow are personalized based on the set preferences in the
cookies.
2

Tracking the pages visited by a user

Setting Cookies with PHP


The setcookie() function is used to set a cookie in PHP. Make sure you call
the setcookie()function before any output generated by your script otherwise
cookie will not set. The basic syntax of this function can be given with:
setcookie(name, value, expire, path, domain, secure);
The parameters of the setcookie() function have the following meanings:

Parameter Description
name The name of the cookie.
value The value of the cookie. Do not store sensitive information since this value
is stored on the user's computer.
expires The expiry date in UNIX timestamp format. After this time cookie will
become inaccessible. The default value is 0.
path Specify the path on the server for which the cookie will be available. If set
to /, the cookie will be available within the entire domain.
domain Specify the domain for which the cookie is available to e.g
www.example.com.
secure This field, if present, indicates that the cookie should be sent only if a
secure HTTPS connection exists.

Example
<?php
setcookie("Name", "sagar", time()+1*60*60, "/mypath/", "mydomain.com", 1); 
?>
Accessing Cookies Values
The PHP $_COOKIE superglobal variable is used to retrieve a cookie value. It
typically an associative array that contains a list of all the cookies values sent by
the browser in the current request, keyed by cookie name. The individual cookie
value can be accessed using standard array notation
Example
<?php
// Accessing an individual cookie value
echo $_COOKIE["Name"];
3

?>
Output sagar
It's a good practice to check whether a cookie is set or not before accessing its
value. To do this you can use the PHP isset() function,
<?php
// Verifying whether a cookie is set or not
if(isset($_COOKIE["name"]))
{
echo "Hi " . $_COOKIE["name"];
}
Else
{
echo "Welcome Guest!";
}
?>

Delete Cookie
You can delete a cookie by calling the same setcookie() function
with the cookie name and any value (such as an empty string) however this time
you need the set the expiration date in the past, as shown in the example below
<?php
// Deleting a cookie
setcookie("username", "", time()-3600);
?>
You should pass exactly the same path, domain, and other arguments that you have
used when you first created the cookie in order to ensure that the correct cookie is
deleted.

Session
A session is a way to store information (in variables) to be used
across multiple pages.Unlike a cookie, the information is not stored on the users
computer
When you work with an application, you open it, do some changes, and
then you close it. This is much like a Session. The computer knows who you are. It
knows when you start the application and when you end. But on the internet there
is one problem: the web server does not know who you are or what you do,
because the HTTP address doesn't maintain state.
4

Session variables solve this problem by storing user information to be


used across multiple pages (e.g. username, favorite color, etc). By default, session
variables last until the user closes the browser.
So; Session variables hold information about one single user, and are available to
all pages in one application.

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 temporary directory and bears the name of
the unique identifier prefixed by sessiesess_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.

Starting a PHP Session


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. Function are use before html tags It is recommended to put the call to
session_start() at the beginning of the page.
Example
<?php
// Start the session
session_start();
?>
Session variables are stored in associative array called $_SESSION[]. These
variables can be accessed during lifetime of a session
Example
<?php
session_start();
// Set session variables
$_SESSION["favcolor"] = "green";
5

$_SESSION["favanimal"] = "cat";
echo "Session variables are set.";
?>
Accessing Session Data
To access the session data we set on our previous example from any other page on
the same web domain — simply recreate the session by calling session_start() and
then pass the corresponding key to the $_SESSION associative array.
Example
<?php
// Starting session
session_start();
// Accessing session data
echo 'Hi, ' . $_SESSION["favcolor"]. ' ' . $_SESSION["favanimal"];
?>
The following example starts a session then register 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.
<?php
session_start();
if( isset( $_SESSION['counter'] ) )
{
$_SESSION['counter'] += 1;
}
else
{
$_SESSION['counter'] = 1;
}
Echo "You have visited this page ". $_SESSION['counter'];
?>
Output
You have visited this page 3

Turning on Auto Session


You don't need to call start_session() function to start a session when a user visits
your site if you can set session.auto_start variable to 1 in php.ini file.

Sessions without cookies


There may be a case when a user does not allow to store cookies on their machine.
So there is another method to send session ID to the browser.
6

Alternatively, you can use the constant SID which is defined if the session started.
If the client did not send an appropriate session cookie, it has the form
session_name=session_id. Otherwise, it expands to an empty string. Thus, you can
embed it unconditionally into URLs.
The following example demonstrates how to register a variable, and how to link
correctly to another page using SID.
<?php
session_start();
if (isset($_SESSION['counter'])) {
$_SESSION['counter'] = 1;
}else {
$_SESSION['counter']++;
}
$msg = "You have visited this page ". $_SESSION['counter'];
$msg .= "in this session.";
echo ( $msg );
?>

<p>
To continue click following link <br />
<a href = "nextpage.php?<?php echo htmlspecialchars(SID); ?>">
</p>
It will produce the following result −

The htmlspecialchars() may be used when printing the SID in order to prevent XSS
related attacks

Destroying a PHP Session


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.

Here is the example to unset a single variable −


<?php
unset($_SESSION['counter']);
?>
Here is the call which will destroy all the session variables −
<?php
7

session_destroy();
?>
PHP Session Encode Decode
in PHP, session encodes and decode operations are
automatically performed while storing session data into memory and reading
stored session, respectively. While encoding, the $_SESSION array is converted
into serialized string format and decoding reverts serialized string back to its
original form. This serialization will not return the same format like PHP
serialize().The encoded session data contains all $_SESSION elements separated
by the semicolon. Each element contains three parts: session index, session length,
and session value
Session Encode Decode functions in PHP
PHP provides functions to perform session encode and decode manually. These
functions are,
 session_encode()
 session_decode()
Before using these functions, we need to start the session using session_start().
Otherwise, we should set session.auto_start directive as 1 in PHP.ini file.
While invoking session_encode() it will take entire $_SESSION global array to
serialize.
PHP session_decode() accepts serialized session data and converts it into an array.
This function returns TRUE on successful decode. session_decode() reloads
$_SESSION array with decoded data.
Example
<?php
session_start();
$_SESSION["product_code"] = "2222";
$_SESSION["logged_in"] = "yes";
$enc_session = session_encode();
print "<b>Encoded Session Data:<br/></b>";
print $enc_session . "<br/><br/>";
// Changing session values
$_SESSION['product_code'] = "2000";
$_SESSION["logged_in"] = "no";
// printing $_SESSION
print "<b>SESSION Array:<br/></b>";
8

print "<pre>";
print_r($_SESSION);
print "</pre>";
session_decode($enc_session);
// printing Reloaded $_SESSION
print "<b>Reloaded SESSION Array:<br/></b>";
print "<pre>";
print_r($_SESSION);
print "</pre>";
?>

Output:
Encoded Session Data:
product_code|s:4:"2222";logged_in|s:3:"yes";
Changed SESSION values:
Array (
[product_code] => 2000
[logged_in] => no
)Reloaded SESSION Array:
Array(
[product_code] => 2222
[logged_in] => yes
)

You might also like