Home > Tutorials > PHP > Cookies and Sessions
Cookies and Sessions
Cookies and Sessions are like memory for your users - cookies are downloaded information about your website (such as login information), and sessions keep track of information temporarily on the server. Using these provide a much more friendly website for everyone.
Cookies
The most common form of information held in a cookie is login information. When you click 'Remember me' on a website login, you are telling the page to give you a cookie with your credentials so you don't have to manually login each time you visit. Of course, there are other types of information that can be stored, too - such as data from an unfinished web game. There are only a few commands you need to know when it comes to cookies:
//Set a Cookie:
setcookie($name,$value,$time);
//Get a Cookie:
$cookie=$_COOKIE[$cookiename];
$name is the name of the cookie you are setting.
$value is the value you are giving this particular cookie.
$time is the length of time (in seconds) that the cookie will be valid. A cookie is automatically deleted from the user's computer when a cookie becomes invalid (to delete a cookie, simply set $time to a negative value).
One thing to note: Cookies must be set BEFORE any output to the screen!
Sessions
Sessions are just like cookies, with one key difference - the information is stored server side, and because of this the information is deleted immediately after the user exits the website. Setting (and deleting) session data is even easier than setting cookies:
//Start session - without this the data won't be saved!
session_start();
//Set session data:
$_SESSION[$varName]=$value;
//unset one specific set of data:
unset($varName);
//delete entire session data:
session_destroy();
Comment on this page:
Comments
No one has commented on this lesson yet. You can be the first!