PHP Sessions

Share this article

is a special array used to store information across the page requests a user makes during his visit to your website or web application. The most fundamental way to explain what a sessions is like is to imagine the following scenario:
You are working with an application. You open it, make some changes, and then you close it.
That is a session in it’s simplest form. The example scenario is reminiscent of the process that happens when using a login system. The process can be extremely complicated or incredibly simple, as long as there is a value that persists between requests. Information stored in the session can be called upon at any time during the open session. While there may be many users accessing the site at the same time, each with his own session, it’s thanks to unique IDs assigned and managed by PHP for each session that allows each user’s session to be available only to himself. Session information is stored on the server rather than the user’s computer (as cookie data is stored), which makes sessions more secure than traditional cookies for passing information between page requests. In this article I’ll give you the low down on using sessions in PHP – how to create them, how to destroy them, and how to make sure they remain secure.

Using Sessions

Before you can to store information in a session, you have to start PHP’s session handling. This is done at the beginning of your PHP code, and must be done before any text, HTML, or JavaScript is sent to the browser. To start the session, you call the session_start() function in your first file:
// start them engines!
// store session data
$_SESSION["username"] = "Callum";
session_start() starts the session between the user and the server, and allows values stored in $_SESSION to be accessible in other scripts later on. In your second file, you call session_start() again which this time continues the session, and you can then retrieve values from $_SESSION.
// continue the session
// retrieve session data
echo "Username = " . $_SESSION["username"];
This example is a very basic demonstration of storing and retrieving data in a session. In the first script, the value “Callum” was associated with the key “username” in the $_SESSION array. In the second script, the information was requested back from the $_SESSION array using the key. $_SESSION allows you to store and retrieve information across the page requests of a user’s active browsing session.

Ending a Session

As important as it is to begin a session, so it is to end one. Even though a session is only a temporary way to store data, it is very important to clean up after yourself to ensure maximum security when dealing with potentially sensitive information. It is also good practice and will avoid having a huge amount of stale session data sitting on the server. To delete a single session value, you use the unset()
// delete the username value
To unset all of the session’s values, you can use the session_unset() function:
// delete all session values
Both examples only affect data stored in the session, not the session itself. You can still store other values to $_SESSION after calling them if you so choose. If you wish to completely stop using the session, for example a user logs out, you use the session_destroy() function.
// terminate the session
I highly recommended that when you are sure you no longer need the session that you destroy it using session_destroy(), rather than just unsetting all of its values with session_unset(). If you just unset all the value, the session itself is still active and malicious code could give those sessions harmful values. That is sessions in a nutshell, the very basic but very powerful functionality within PHP that provides an elegant solution to the problem of passing data between web pages.

Session Security Tips

Despite there simplicity, there are still ways using sessions can go wrong. Here is a quick overview of some security techniques you can use to ensure you are using sessions safely.

Session Time-Outs

Timing-out sessions is a very important action if you are dealing with users logged in to your website or application. If a user logs in to your site in an Internet café and then leaves the computer and café without logging out, how do you stop the next user on that computer from still having access to the previous user’s session? Well you can use the following code:
// set time-out period (in seconds)
$inactive = 600;

// check to see if $_SESSION["timeout"] is set
if (isset($_SESSION["timeout"])) {
    // calculate the session's "time to live"
    $sessionTTL = time() - $_SESSION["timeout"];
    if ($sessionTTL > $inactive) {
        header("Location: /logout.php");

$_SESSION["timeout"] = time();
The code ensures that if there is no activity for more than 600 seconds (10 minutes) the request is redirected to the logout page which would successfully log out the user.

Regenerate the Session ID

The session_regenerate_id() function creates a new unique-ID for to represent the current user’s session. This should be regenerated time any important authentication action is performed, such as logging in or updating user profile data. Giving the sessions a new ID after such actions make your application more secure by reducing the risk of a specific attack known as “Session Hijacking.”

if ($_POST["username"] == "admin" && $_POST["password"] == sha1("password")) {
    $_SESSION["authorized"] = true;

Destroy Sessions

As I previously mentioned, you should use session_destory() once you don’t need to use the session any more. This stops attackers from hijack the stale session, again increasing the session-related security of your web site.

Use Permanent Storage

Use a database to store data at the earliest moment you know the data will be persistent; don’t let it stay as part of the session for too long as this opens it up to possible attack. Really think about whether the data belongs should be stored in $_SESSION because session data is meant to be transient.


In this article you’ve learned what a session is, and how to create, use, and destroy them in PHP. You also saw a few tips to ensure they remain secure. For more information on sessions and session security, please check out these suggested articles and web pages: Image via Kokhanchikov / Shutterstock And if you enjoyed reading this post, you’ll love Learnable; the place to learn fresh skills and techniques from the masters. Members get instant access to all of SitePoint’s ebooks and interactive online courses, like Jump Start PHP. Comments on this article are closed. Have a question about PHP? Why not ask it on our forums?

Frequently Asked Questions about PHP Sessions

What is a PHP session and why is it important?

A PHP session is a way to store information (in variables) to be used across multiple pages. Unlike a cookie, the information is not stored on the users’ computer. PHP sessions are important because they help to maintain data across subsequent accesses. This means you can build more customized applications and increase the relevance of the process for your users. For example, sessions can be used to store user login details or shopping cart items for a user while they browse around your website.

How do I start a PHP session?

To start a PHP session, you use the session_start() function. This function first checks if a session is already started and if none is started then it starts one. It is recommended to put the call to session_start() at the beginning of the page.

How can I store data in a PHP session?

You can store data in a PHP session by setting the $_SESSION variable. This is a global variable and can be accessed from anywhere in your PHP script. For example, to store a user’s username, you could use $_SESSION[“username”] = “John Doe”.

How can I retrieve data from a PHP session?

You can retrieve data from a PHP session by accessing the $_SESSION variable. For example, to retrieve a user’s username, you could use echo $_SESSION[“username”].

How can I destroy a PHP session?

You can destroy a PHP session by using the session_destroy() function. This function does not need any argument and a single call can destroy all session variables. If you want to destroy a single session variable then you can use unset() function.

What is the difference between a session and a cookie?

The main difference between a session and a cookie is that sessions are stored on the server, while cookies are stored on the user’s computer. This makes sessions more secure than cookies, but it also means that sessions can take up more server resources.

How can I check if a PHP session has already started?

You can check if a PHP session has already started by using the session_status() function. This function returns the current session status, and can be used to avoid errors if you try to start a session that has already started.

Can I use sessions if cookies are disabled on the user’s browser?

Yes, you can use sessions even if cookies are disabled on the user’s browser. PHP will pass the session ID via the URL if it cannot set it in a cookie.

How secure are PHP sessions?

PHP sessions are quite secure as they are stored on the server. However, the session ID passed in the URL can be intercepted and used to hijack the session. To prevent this, you can use the session_regenerate_id() function to change the session ID periodically.

Can I store objects in a PHP session?

Yes, you can store objects in a PHP session. You can serialize objects before storing them in a session and unserialize them when retrieving.

Callum HopkinsCallum Hopkins
View Author

Callum Hopkins is a designer and front-end developer with over 6 years web experience and has a Bachelors degree in Design for Digital Media. With knowledge in both design and development he is able to influence both sides of the web building process, and has a love for complex coding functions and beautiful design. Callum works as a developer for Deer Digital LTD and runs his own personal blog at where he writes thought provoking articles.

Share this article
Read Next
Get the freshest news and resources for developers, designers and digital creators in your inbox each week
Loading form