April 17th, 2008
Learn PHP From Scratch - Part XIX
PHP Sessions
As a website becomes more sophisticated, so must the code that backs it. When you get to a stage where your website need to pass along user data from one page to another, it might be time to start thinking about using PHP Sessions.
PHP Sessions - Introduction
A PHP session solves this problem by allowing you to store user information on the server for later use (i.e. username, shopping cart items, etc). However, this session information is temporary and is usually deleted very quickly after the user has left the website that uses sessions.
It is important to ponder if the sessions’ temporary storage is applicable to your website. If you require a more permanent storage you will need to find another solution, like a MySQL database.
Sessions work by creating a unique identification(UID) number for each visitor and storing variables based on this ID. This helps to prevent two users’ data from getting confused with one another when visiting the same webpage.
Note:If you are not experienced with session programming it is not recommended that you use sessions on a website that requires high-security, as there are security holes that take some advanced techniques to plug.
Starting PHP Session
Before you can begin storing user information in your PHP session, you must first start the session. When you start a session, it must be at the very beginning of your code, before any HTML or text is sent.
Below is a simple script that you should place at the beginning of your PHP code to start up a PHP session
1 2 3 4 5 | <?php session_start(); // start up your PHP session! ?> |
This tiny piece of code will register the user’s session with the server, allow you to start saving user information and assign a UID (unique identification number) for that user’s session.
Storing a Session Variable
When you want to store user data in a session use the $_SESSION associative array. This is where you both store and retrieve session data. In previous versions of PHP there were other ways to perform this store operation, but it has been updated and this is the correct way to do it.
1 2 3 4 5 6 7 | <?php session_start(); $_SESSION['views'] = 1; // store session data echo "Pageviews = ". $_SESSION['views']; //retrieve data ?> |
The output is:
Pageviews = 1In this example we learned how to store a variable to the session associative array $_SESSION and also how to retrieve data from that same array.
Pages : 1 2

