Professional Documents
Culture Documents
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
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["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
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
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
)