26 COOKIE and SESSION
Hiren Joshi
Objectives
• Cookie
• Session
COOKIE
- In any web application, it is essential to keep track of users as he/she moves in a web pages of web application. To keep track of user’s movement within a web application session and cookies are used.
- Cookie provides a way for web application to store information in the user’s web browser and can retrieve the information of cookie every time as and when the user request a page.
- Cookie is a name=value pair which is stored on user’s browser.
- On the server, cookie is created by web application and sends it to browser.
- On the client, the cookie is saved in the browser and sends it back to the server each time when server access a page.
- By default, cookie exists till the user’s browser is open. However, it can be store in the user browser for maximum 3 years by set to persistent cookie.
- Cookie can be disabled in the browser by user. So you cannot always count that cookie is enabled by all the users.
- Browser generally accept
- 20 cookies from each site
- 300 cookies in total
- Maximum storage capacity for each cookie is 4 kilobytes
- Cookie can relate to one or more sub domain names.
Most common uses for cookies are
- To Allow users to skip login and registration forms: Cookie can gather data like username, password , address or credit card number. By using this stored data, user can skip login and registration forms data.
- To Customize Pages: Cookie can customize pages as per user choices and display information like sports score, weather information and stock price.
- To Focus advertising: Cookie can be used for advertising like banner ads which is used to target user’s interest.
Third party cookie
- The common misconceptions are that cookies are harmful because they can store user information and retrieve each time.
- There are rumors like cookie can transmit viruses, steal passwords and copy file from user’s hard-disk. Although these rumors are not true, cookies can be misused sometimes. For example, some advertisers use cookie to track the web site visited by users. These cookies are known as third party cookie because it is sent from advertisers, not by the user’s visited website.
- To fight with third party cookies, modern web browsers are facilitated to block third party cookies by changing browser options.
- Cookies are consisted of plain text so they cannot directly modify user’s computer, generate span, steal files or create pop-up ads.
Set Cookie
- To set a cookie setcookie function is used
- setcookie function creates a cookie and set it in the browser.
- Setcookie function must be called before any HTML output is sent from the application.
- Cookies can be classified as
- Per-session
- Persistent
- Per-session cookie exists till the browser is open.
- Persistent cookie exists till the specified expiration date.
- The syntax to setcookie is shown below
setcookie($name, $value, $expire, $path, $domain, $secure, $httponly)
Where
• $name is the name of the cookie
• $value is the value of the cookie. By default value is empty string
• $expire is the expiration date of cookie in timestamp format. Default value is 0 which means it is a per-session cookie.
• $path is the path on the server to available cookie. To make available cookie to all the directories on the current server, $path is set to ‘/’’. Default directory is the directory of PHP file which setting’s the cookie.
• $domain is the domain where cookie is available. Default is the name of the server that setting’s the cookie.
• $secure is true or false. True means cookie is only available if it is sent using https.
• $httponly is true or false. True means cookie is only available http protocol only. It is not available through client side scripting language such as java script. Default value is false.
Following example shows how to set a cookie
<?php
$name = ‘Hiren’;
$value = ‘password’;
$exp = time() + 86400;
echo “<br> $exp”;
setcookie($name,$value,$exp);
echo “<br> Cookie is set”;
?>
The output of the above code is:1502354508 Cookie is set
Get Cookie
- To get the value of stored cookie, $_COOKIE super global variable is used
- $_COOKIE is an associative array.
- In $_COOKIE associate where array cookie name is key and cookie value is a value
Following example shows how to get a cookie value
<?php
$name = $_COOKIE[‘Hiren’];
echo “<br> The value of cookie is :”. $name;
?>
The output of the above code is:The value of cookie is :password
Delete Cookie
- To delete a cookie from browser, code the cookie with the same name as the time of set it, set value to empty string and set expiration attribute is the past date.
- All other remaining parameters value must be the same when cookie was created.
Following example shows how to delete a cookie
<?php
$expire = time() – 86400;
$name = ‘Hiren’;
setcookie($name,”,$expire);
if(isset($_COOKIE[‘Hiren’]))
{
echo “<br> Cookie is set”;
}
else
{
echo “<br> Cookie is not set”;
}
?>
The output of the above code is:Cookie is not set
Enabled or Disabled Cookie in a browser
• To test the behavior of application when cookie is disabled, cookie can be disabled.
• To test the behavior of application when cookie is enabled, cookie can be enabled
• For example, to display a message which shows that the cookies are required for the application to function properly.
• How to enabled or disabled cookie is depended on browser.
• Following code shows how you can view cookies in your browser.
<?php
$name = ‘Hiren’;
$value = ‘password’;
$exp = time() + 86400;
echo “<br> $exp”;
setcookie($name,$value,$exp);
echo “<br> Cookie is set”;
setcookie(‘Age’,19,$exp);
echo “<br> 2nd Cookie is set <br>”;
print_r($_COOKIE);
?>
The output of the above code is shown below
1502386488
Cookie is set
2nd Cookie is set
Array ( [Hiren] => password [Age] => 19 )
- To view the cookie in chrome browser, go to settings -> show advance settings -> privacy ->content settings->All cookies and site data->localhost
- It will display all the information of each cookie like Name, content, domain, path created and expires.
SESSION
- Session tracking is a technique to keep track of the user’s movement around the website.
- Session tracking is used to maintain the state in a web application.
- HTTP is a stateless protocol. So once a browser send request to the server, and server responds to the browser, the connection between browser(client) and server is dropped.
- Cookie is used to store a SessionID in each browser by default. Then, the cookie is passed by the browser to the server for each request.
- URL encoding is used to store sessionID in the URL of each page of an application when cookie is disabled.
Why session tracking is difficult with HTTP
As shown in above figure, the browser send a first HTTP request to the web server. The web server response the browser by sending the requested page and the connection between browser and web server is dropped. For the following HTTP requests from web browser, the web server has no way to associate the web browser with its previous request.
How PHP keeps track of session
As shown in above figure, the browser sends the first HTTP request to the web server. The PHP engine creates a session and assign ID to it. The web server sends the requested page and ID for the session as a cookie it to the browser. For the following HTTP requests, web browser sends the session ID cookie to the web server. PHP uses the session ID to associate browser with its session.
SESSION START
• Though session starting is built in to PHP, it is not automatically start.
• To start a new session or resume the previous session, session_start function must be called at the starting of each page in the application which needs to access session data.
• session_start function prompts PHP to check sessionID in the request and in case , it is not available, session_start function creates a new sessionID and session cookie.
• Session_start function may set a cookie, so it must be called before any HTML output sent to the browser.
• By default, per-session cookie is used to store the sessionID in the user’s browser by PHP.
Method | Description |
session_start( )
|
Start a new session or resume the previous session. This
function must be called before any HTML output sent to the browser by the page. Returns true if successful otherwise false. |
• session_start( ) function Starts the session with default cookie parameter.
• <?php
• session_start();
• echo “<br> Session is started”;
• ?>
Session cookie
- To control, how session cookie works, session_set_cookie_params function is used.
- session_set_cookie_params is used to set the parameters of the session cookie.
- session_set_cookie_params ($lifetime, $path, $domain, $secure, $httponly)
- Where
- $lifetime is the timespan of session cookie in seconds in which cookie is live. Default is 0.
- $lifetime is the only compulsory parameters. All other parameters are optional for session_set_cookie_params function.
<?php
//Start a session with Custom cookie parameters $lifetime = 60 * 60 * 24 * 7 ; //1 week session_set_cookie_params($lifetime , ‘/’); session_start();
echo “<br> session is started <br>”;
$ans = $_COOKIE[‘PHPSESSID’];
echo “<br> Value of session cookie is : “.$ans; ?>
session is started
Value of session cookie is : dn8p6792bs1el76o9mco1rjka7
Get and Set Session Variable
• Once a session is start, $_SESSION variable is used to set and get the user’s data for the session.
• $_SESSION variable is an associative array.
• isset function can be used to test if an element already exist in the $_SESSION array.
• To remove an element from the $_SESSION array, the unset function is used.
• However the unset function should not use on the $_SESSION array itself as it can cause unpredictable results.
• $_SESSION array should be set to an empty array to remove its contents.
<?php
//Set a variable in session
$_SESSION[‘pcode’] = ‘ABC-1234’;
//Get a varibale from a session
$productcode = $_SESSION[‘pcode’];
echo “<br> Product Code is: $productcode”;
?>
Product Code is: ABC-1234
Set and Get arrays
<?php
//Set an array in a session
If(!isset($_SESSION[‘cart’]))
{
$_SESSION[‘cart’] = array();
}
//Add an element to an array that is stored in a session $_SESSION[‘cart’][‘pcode1’] = ‘value1’;
$_SESSION[‘cart’][‘pcode2’] = ‘value2’;
//Get and use an array that’s stored in a session $cart = $_SESSION[‘cart’];
foreach($cart as $p=>$item)
{
echo ‘<li>’.$p. ‘:’ . $item.'</li>’;
}
?>
The output of above code is:
- pcode1:value1
- pcode2:value2
Remove variables from session
- To remove a session variable, unset function is used. The unset function should not be used to remove all $_SESSION array itself because it can cause unpredictable result.
- To remove all session variables, $_SESSION array can be set to an empty array.
- Following code shows how to remove a session variable
<?php
If(!isset($_SESSION[‘cart’]))
{
$_SESSION[‘cart’] = array();
}
//Add an element to an array that is stored in a session $_SESSION[‘cart’][‘pcode1’] = ‘value1’; $_SESSION[‘cart’][‘pcode2’] = ‘value2’;
//Get and use an array that’s stored in a session $cart = $_SESSION[‘cart’]; foreach($cart as $p=>$item)
{
echo ‘<li>’.$p. ‘:’ . $item.'</li>’;
}
//Remove a session variable if(empty($_SESSION[‘cart’]))
{
echo “<br> Session cart is unset”;
}
else
{
echo “<br> Session cart is set”;
}
unset($_SESSION[‘cart’]);
if(empty($_SESSION[‘cart’]))
{
echo “<br> Session cart is unset”;
}
//Remove all session variable
$_SESSION = array();
//to display
/*
$cart = $_SESSION[‘cart’];
foreach($cart as $p=>$item)
{
echo ‘<li>’.$p. ‘:’ . $item.'</li>’;
}
*/
?>
The output of the above code is:
pcode1:value1
pcode2:value2
Session cart is set
Session cart is unset
End Session
• A session ends
• when the browser is closed by the user,
• when a request is not received within specified amount of time (by default 24 minutes )or
• when the session_destroy function is called .
• To remove all data from the client and the server associated with the session,
• the session data are cleared from memory
• the session_destroy function is called and
• the setcookie function is used to delete the session cookie.
• To get the name of the session cookie, session_name function is used.
• The session cookie by default name is “PHPSESSID”
• The session_get_cookie_params function is used to gets an associated array that contain all of the parameters for the session cookie. The parameters are same as session_set_cookie_params
Function to end a session
• session_destroy()
• Ends a session. Returns TRUE if successful and FALSE otherwise.
• End a session
//clear session data from memory
$_SESSION = array();
// Clean up the session ID session_destroy();
Delete the session cookie from the browser
<?php
//Delete the session cookie from the browser
// Get name of session cookie $name = session_name();
// Create expire date in past
$expire = strtotime(‘-1 year’);
// Get session parameters
$params = session_get_cookie_params();
$path = $params[‘path’];
$domain = $params[‘domain’];
$secure = $params[‘secure’];
$httponly = $params[‘httponly’];
setcookie($name,”, $expire, $path, $domain, $secure, $httponly);
if(isset($_COOKIE[$name]))
{
echo “<br> Session cookie is set”;
}
else
{
echo “<br> Session cookie is not set”;
} ?>
Output:
Session cookie is not set
Functions to manage sessions
Function | Description |
session_name( ) | Get the name of session cookie. By default name is PHPSESSID. |
session_id([$id ])
|
Set the session is to $id. If parameter $id is not provided, this
function gets the current session id. If no session exists, this function returns empty string. |
session_write_close( )
|
Close the current session and saves session data. It is only required
in special case like redirects |
session_regenerate_id( )
|
Creates a new session id for the current session. This function can
be used to help to prevent session hijacking.It returns true if successful otherwise returns false. |
Example
<?php
//Get the name of the session cookie
// by default PHPSESSID
$name = session_name();
echo “<br> Session name is : “.$name;
//Get the value of the session ID
// for example,
$id = session_id();
echo “<br> Session id is : “.$id;
//Set the session ID
session_id(‘abc123’);
$newid = session_id();
echo “<br> New Session id is : “.$newid;
?>
Output:
Session name is : PHPSESSID
Session id is :
New Session id is : abc123
you can view video on COOKIE and SESSION |
References:
1. Luke Welling, Laura Thomson: PHP and MySQL Web Development, Pearson,
2. W. Jason Gilmore: Beginning PHP and MySQL 5 From Novice to Professional, Apress
3. Elizabeth Naramore, Jason Gerner, Yann Le Scouarnec, Jeremy Stolz, Michael K. Glass:
Beginning PHP5, Apache, and MySQL Web Development, Wrox,
4. Robin Nixon: Learning PHP, MySQL, and JavaScript, O’Reilly Media
5. Ed Lecky-Thompson, Heow Eide-Goodman, Steven D. Nowicki, Alec Cove: Professional PHP,Wrox
6. Tim Converse, Joyce Park, Clark Morgan: PHP5 and MySQL Bible
7. Joel Murach, Ray Harris: Murach’s PHP and MySQL, Shroff/Murach
8. Ivan Bayross, Web Enabled Commercial Application Development Using HTML/Javascript/DHTML/PHP , BPB Publications
9. Julie C. Meloni, Sams Teach Yourself PHP, MySQL and Apache All in One, Sams
10. Larry Ullman, PHP and MySQL for Dynamic Web Sites: Visual QuickPro Guide, Pearson Education
11. http://www.php.net/
12. http://www.w3schools.com/
13. http://www.tutorialspoint.com/