Sessions and cookies. What are they? Smoking marijuana and eating biscuits? Hell no, in the web development world these are very important things. The difference between sessions and cookies is basically just where they are stored.
Let’s start with sessions: They are pieces of data that are recorded by a web script that is stored on the server, and can be programmed to last for a certain amount of time, but usually gets erased when the user shuts their browser, although it is required that the function session_start() be called before ANY output is sent to the browser. To be on the safe side, I usually put it on the first line of code in a web script. The easiest way to create and manage sessions in PHP (4+) is as follows:
<?
session_start();
$_SESSION[‘session_name’] = ‘your data’;
?>
You can use this same variable to compare with other strings in if statements etc.
If for any reason you wish to erase a session before the user shuts their browser, you use session_destroy():
<?
session_destroy(‘session_name’);
?>
Let’s write a simple sessions script:
<?
session_start();
echo ‘Welcome to our sessions test! Your example username can be pogo!’;
$_SESSION[‘username’] = ‘pogo’;
echo ‘<a href=”page2.php”>Click here to have a session</a>’;
?>
And now for page 2:
<?
session_start();
echo ‘If all goes well, your username should show as “pogo”.’;
$username = $_SESSION[‘username’];
echo ‘Username: ‘.$username;
echo ‘Welcome pogo!’;
?>
Ofcourse this script has no user entered data, but that is only one modification away (adding an HTML form). I think this example is sufficient enough to demonstrate how sessions work.
Yep, that’s so simple even a monkey could do it, and people say sessions are hard! Pfft!
Now on to cookies (mmmmm). Cookies are the same thing as sessions basically except that they are stored locally (on your PC). If you are using M$ Windows then the chances are they are stored in [windows default folder]\Cookies, although if you have profiles they will be located in your personal profile’s cookie folder.
They are used the same way as the sessions are above, with SESSION replaced with COOKIE:
<?
$_COOKIE[‘cookie_name’] = ‘your data’;
$name = $_COOKIE[‘cookie_name’];
echo $name;
// this outputs “your data” on your page
?>
You can use the same example script as provided for the sessions tutorial above, replacing “SESSION” with “COOKIE”.
There are more complicated ways of registering cookies which I wont go into because this is a basic tutorial, although I will outline it. The function is the same function used except for PHP server versions that are version less than 4 (or 4+ aswell). They have extra attributes that allow you to set the timeout limit, domain, cookie name, data, etc.
For more imformation on sessions, follow the following link:
http://nz2.php.net/manual/en/functio...n-register.php
For more information on cookies, follow the following link:
http://nz2.php.net/manual/en/function.setcookie.php