In this tutorial I will talk about using sessions in PHP; there will be a description an a small example to demonstrate how sessions are working.
What is a session?
Usually web pages are “stateless”, which means that each request is handled like a new one without knowing anything about the previous requests. In this way will be hard to access a website using a predefined variable like a username and a password because the typed values would be lost. To avoid this problems, webservers have ways to remember the previous visits on other pages on the website, everything being threated as a single, one work session. The sessions can be identified (to have acces only after login) and they have to keep informations like username, an id, passwords etc..) on their duration.
The values, in PHP, are kept in $_SESSION a special, predefined variable for sessions. The tehnical way on keeping the sessions is through cookies. This identifier is kept on the server and expires after a certain amount of time. Is randomly generated and cannot be guessed.
A session must be opened, can be closed and there are some functions on dealing with them:
- session_start() – initializes a new session.
- session_register() – registers a variable name as beeing part from a session.
- session_unregister() – unregisters a variable name from a session.
- session_unset() – deletes all the data kept in a session.
And now some code:
echo 'Page #1';
$_SESSION['time'] = time();
echo '<br /><a href="testsession2.php?' . SID . '">page 2 with session</a>';
echo 'Page #2<br/>
Time: '.date('Y m d H:i:s').
'<br />Initial time (from session): '.date('Y m d H:i:s', $_SESSION['time']);
We have to pieces of code. You can put them in two separate pages, run them an see the result!
You can refresh the second script (if you add it in a php page) and you will see that the initial time remains the same, from the session. PHP handles the sessions automatically. An important thing, to keep in mind is that you need to keep as less data as possible in a session, because for very large websites it can be tricky, because it will eat up a lot of RAM.
I hope you like this tutorial about Sessions in PHP.