Check to see if a session has already been started in PHP.

This is a PHP guide on how to check to see if a session already exists.

As you probably already know, session_start is an in-built PHP function that will create a new session.

However, if you call this function more than once, your script will throw an E_NOTICE error.

Although the solution seems pretty straight forward (do not call it more than once), in certain scenarios, you won’t be entirely sure if a session has already been started or not. In some cases, it might be out of your control.

There are two ways to approach this.

Checking to see if a session exists in versions lower than 5.4.

If you are using a PHP version that is lower than 5.4.0, you can do the following.

<?php
if(session_id() == ''){
    //session has not started
    session_start();
}

var_dump(session_id());

If you run the code above, you will see that a session is always present.

This is because.

  1. We check to see if the function session_id returns an empty string.
  2. If the session_id function returns an empty string, then we can presume that a session does not exist.
  3. If this is the case, we can simply start the session by calling the function session_start.

Using the session_status function in PHP 5.4 and above.

In PHP version 5.4.0 and above, we can use the session_status function. As the name suggests, this function returns the status of the current session.

This function can return three different integer values, all of which are available as predefined constants. These are:

  • 0 – PHP_SESSION_DISABLED: Sessions are currently disabled.
  • 1 – PHP_SESSION_NONE: No session exists.
  • 2 – PHP_SESSION_ACTIVE: A session already exists.

If we were to use session_status, our code would look like this:

if(session_status() == PHP_SESSION_NONE){
    //session has not started
    session_start();
}

As you can see, using this function makes your code a little more self-explanatory!

Why not just check if the $_SESSION array is empty?

You can check to see if the $_SESSION array exists and is not empty. However, it is worth noting that $_SESSION can be manually created like so.

<?php
$_SESSION = array(
    'test' => true
);

In other words, the $_SESSION array might exist even if no session is present.

Another issue is that this array can be empty, even if a session already exists.