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

The problem is:

  • If you call it more than once, your script will throw an E_NOTICE error.
  • Although the solution seems pretty straight forward (don’t 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.

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

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

var_dump(session_id());
  • If you run the code above, you’ll see that a session is always started. This is because:
  • We check to see if the function session_id returns an empty string.
  • If session_id returns an empty string, we can conclude that the session has not been started yet.
  • If this is the case, we can start the session by calling the function session_start.
  • In PHP version 5.4.0 and above, we can make use of the function session_status, which 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:

Php Code
<?php
if(session_status() == PHP_SESSION_NONE){
//session has not started
session_start();
}

[ad type=”banner”]

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

Note that you can also check to see if the $_SESSION array has been set. However, it is worth noting that $_SESSION can be manually initialized like so:

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

i.e. The $_SESSION array might exist, even if a session hasn’t already been started.

Php Code
if (version_compare(phpversion(), '5.4.0', '<')) {
if(session_id() == '') {
session_start();
}
}
else
{
if (session_status() == PHP_SESSION_NONE) {
session_start();
}
}

Prior to PHP 5.4 there is no reliable way of knowing other than setting a global flag.

Consider:

Php Code
var_dump($_SESSION); // null
session_start();
var_dump($_SESSION); // array
session_destroy();
var_dump($_SESSION); // array, but session isn't active.
Php Code
session_id(); // returns empty string
session_start();
session_id(); // returns session hash
session_destroy();
session_id(); // returns empty string, ok, but then
session_id('foo'); // tell php the session id to use
session_id(); // returns 'foo', but no session is active.

[ad type=”banner”]

Sample code:

Php Code
if (!isset($_SESSION)) session_start();

Categorized in: