Thursday, 9 August 2018

Check To See If A Session Has Already Been Started In PHP

This is a simple guide on how to check to see if session_start has already been called in PHP.
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:
If you run the code above, you’ll see that a session is always started. This is because:
  1. We check to see if the function session_id returns an empty string.
  2. If session_id returns an empty string, we can conclude that the session has not been started yet.
  3. 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:
  • 0 – PHP_SESSION_DISABLED: Sessions are currently disabled.
  • 1 – PHP_SESSION_NONE: Sessions are enabled, but no session has been started.
  • 2 – PHP_SESSION_ACTIVE: Sessions are enabled and a session has been started.
If we were to use session_status, our code would look like this:
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:
i.e. The $_SESSION array might exist, even if a session hasn’t already been started.

0 comments:

Post a Comment