Sessions are similar to cookies but their differences are important to note. Sessions are not stored on a user's computer and users usually cannot disable session functionality. The downside to sessions is that they are lost once the user closes their browser.
Have you ever been logged into a website and then close your browser only to find that you are logged out once you reopen it? Chances are, the website was using a session to store your login data.
So cookies are a bit more permanent than sessions. Once you understand the features of both you will be able to use a combination of them to suit all your needs.
Before sessions can be used on a PHP page, there must be a call to the session_start function. This tells the PHP interpreter that you will be using sessions on this page. After that, you set whatever you want using the $_SESSION variable as shown below:
session_start(); $_SESSION['variable'] = 'whatever';
You must call the session_start function before any other output is sent to the user, or else it will not work.
Let's look at a working example of sessions in action with the following PHP script:
<?php session_start(); // we must always call this function if (isset($_SESSION['visits'])) // has our session variable been set? { echo 'You have been here ' . $_SESSION['visits'] . ' times before'; $_SESSION['visits']++; // increase the counter variable } else { echo 'This is your first time here'; $_SESSION['visits'] = 1; } ?>
The first time you run the code above, the script will tell you that it is your first time there. If you refresh the page, you will see your number of visits increasing. If you want to reset the counter, you will have to close your browser and reopen it.
If you want to delete a particular session variable you would use some code like this:
<?php unset($_SESSION['visits']); ?>
And if you want to forget everything about the session (and not only a single variable) you can use the following:
<?php session_start(); session_destroy(); ?>
Note that you must make a call to session_start before you can call session_destroy! That might seem strange but we still need to let PHP know that we are working with sessions on the particular page as per usual.