By Callum Hopkins

PHP Sessions

By Callum Hopkins

$_SESSION 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() function:

// 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?

  • Helen Natasha Moore

    Great article, but annoying to read about a male user all the way through :-(

    • I’m sorry that stood out for you, Helen. :( English doesn’t really have a proper gender-neutral singular pronoun (writing “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 itself” would be ambiguous), and using a plural form is not grammatically correct. As managing editor though I can say the writers and myself do our best to be conscious of the sensitivities of others. For example, she/her is used in Getting Started with PHPUnit, Preventing Cross-Site Request Forgeries, and Variables in PHP. Neither SitePoint nor PHPMaster condone discrimination on the basis of gender, race, religion, sexual orientation, etc. and I would hope our content reflects such values.

    • John

      Wow Helen get a grip, yea he probably could’ve said their instead of his in one instance but in the entire article there are only two instances of a specific gender being refered to. talk about sensitive!

    • Hi Callum
      There could have been an example where you want to elongate the session past the 20 minute standard e.g. for the data entry operators.



    • Tyrone

      helen ya’ll need to chill

  • Stoyan Yordanov

    Very useful article, especially in the security field! Thank you!

  • Navid Emami

    It was a good article covering most important topics in session and it could be better to use these tips inside a class, i mean the object-oriented way…

  • Reen

    After a location header you should die, otherwise the rest of the code is executed, without a session, wich can lead to security issues.

    Also session timeout is a php.ini setting, why implement it yourself?

    And what is this?
    $_POST[“password”] == sha1(“password”)
    First, you’re using SHA-1, second you didn’t even hash the password, it is still plain text in the sourcecode.

    • Bob

      Whats wrong with sha-1? I’m just curious – learning here.

  • I just wanted to say, to everyone at “phpmasters” that, and as a fellow PHP/JavaScript beginner, I have been gleaning so much knowledge and information from ALL of these posts, I just didn’t know where to put it! Keep up the great content, nice post here too Callum. Cheers!

  • Emile

    The link in the Summary: “PHP Manual – Sessions” contains a typo:
    The false link is:
    The correct link is:

  • Every web app I work on, whether my own or someone else’s, I use a custom sessionManager class that uses DB (PostgreSQL but MySQL works too) for sessions – and is specific to the web app. It also caches the sessions in APC (obfuscating the ID with sha1sum(salt + $sid). Nice thing about caching the session is that in most cases, the session info is readily available when a script runs, no file I/O or DB call is needed, it’s in cache. When writing, you have to write to both APC and to the DB but since php sessions do not write session data until after script has finished executing, that DB call does not slow down page load.

    With respect to security, one mistake many web sites make is they share a SID between standard http and https. A better thing to do is record the connection type as a session variable. When a secure page is requested, the session script sees the previous page was not secure and regenerates the session ID (and sends the new cookie SSL only). That prevents a SID that was stolen from a non secure request from being used after the legitimate user successfully authenticates over SSL.
    OT NOTE – you are using JS for syntax highlighting. The version of the widget you are using interferes with copying code via mouse. The “copy to clipboard” option does not work with recent versions of flash. Just a note, it’s a pet peeve of mine how broken that JS is from a usability stand point (current version of that widget is much better, though I still don’t like it).

  • burak

    Sould I use that session_start() all my php files in my site?
    include index.php checkpass.php edit.php. delete.php logout.php

  • KS

    Would like to see an article about session hijacking. Not clear to me that regenerating session id on login really mitigates that issue. Thanks!

  • Steve205

    How do u ensure the session file gets deleted when the user closes the web browser or tab? Meaning, they do not invoke the logoff routine?,,py

  • Hi, my understanding is that the PHP server will create a cookie on the client machine/browser with the sessionid unless the script/server is configured otherwise. Is that correct? There are arguments as to the safest way to keep the session active, whether through a cookie, GET or POST. What is your opinion? I would say the cookie is the safest way if you use random ids etc.

  • N00Bian

    Im just starting out in all this session hoopla, … how is sessions any safer than cookies, after all the sessionid is sent via the headers…

  • here a good tutorial on session security i found while searching,-protection-3.html

  • good example of session tutorial.

  • Vincent

    I have a problem.
    When logging in, I started the session and set a session variable $_SESSION[“user”].But checking up that variable on another secured page is a problem. Its returning an empty variable.
    But You know what, it works very well on my machine, but after uploading it on my website, it keeps returning empty variable. What do I do about this. The code snippet are:

    $_SESSION[“user”]= “admin”;
    header(“Location: index.php”);


    if ($pass!=’admin’ )
    header(“Location: login.php”);

  • Nick

    For the PHP session timeout, that means people can’t be idle on a page. They could be just reading an article for an hour (and not switching between pages to restart the timeout) and when they click another link (that requires a session) they would be logged out. Is there another way to do this – I’m interested in the idea of being secure.

  • Jed

    I’m thinking this won’t work:

Get the latest in PHP, once a week, for free.