Monday, May 9, 2011

Difference between Cookies and Sessions

Cookies

There is a function setcookie() for cookie manipulation. This function allows reading and writing cookie files, as demonstrated in the following example:

<?php 

if (!isset ($_COOKIE['visited'])) { 
// if a cookie does not exist set it 
setcookie("visited", "1", mktime()+86400, "/") or die("Could not set cookie"); 
echo "This is your first visit here today."; 

else { 
// if a cookie already exists 
echo "Nice to see you again, old friend!"; 
?>


To see how this works, request the page above through browser a couple of times. The first time around, because no cookie has yet been set, the first message will be displayed. On all subsequent attempts, because the cookie has already been set, the client will be recognized and the second message will be displayed. Note that this works even if you terminate the browser instance, restart it and visit the page again. The setcookie() function accepts six arguments: the name of the cookie, its value, its expiry date, the domain, the path for which it is valid, and a Boolean value indicating its security state. Cookie values are automatically sent to PHP from the client, and converted to key-value pairs in the $_COOKIE variable, a super global array similar to $_SESSION.

Sessions
This is a simple counter that initializes a variable the first time you visit a Web page, and increments it each time you reload the page. The counter variable is stored in a session, which means that if you browse to another site and then return, the last saved value of the counter will be restored.

<?php 
session_start();                                                // initialize a session 

$_SESSION['counter']++;                              // increment a session counter
echo "You have viewed this page " . $_SESSION['counter'] . " times";      // print value  
?> 


To see how this works, request the script above through your browser a few times. You will notice that the counter increases by 1 on each subsequent page load. If you open up two browser windows and request the same page in each one, PHP will maintain and increment individual session counters for each browser instance. The session ID is used to identify which client made which request, and recreate the prior saved environment for each individual session. This also means that if you visit one (or more) other Web sites during the same session and then return to the script above without shutting down your browser in the interim, your previous session will be retrieved and recreated for you. Every session in PHP begins with a call to the session_start() function. This function checks to see whether a session already exists, and either restores it (if it does) or creates a new one (if it doesn't). 

No comments:

Post a Comment