How to Check if PHP session has already started?


In PHP,we utilize session_start() an inbuilt function to start the session .But the problem we face in a PHP script is if we execute it more than once it throws an error. So here we will learn how to check the session started or not without calling session_start() function twice.

There are two ways to follow to resolve this problem.

For below PHP 5.4.0 version.

Example

<?php
   if(session_id() == ''){
      session_start();
   }
?>

Explanation

If the session not started this code above will always start the session in the PHP script.

In the second method, we can utilize the function session_status(), which returns the status of the present session. This function can return three integer values, which all are 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.

Example:

<?php
   if (session_status() == PHP_SESSION_NONE) {
      session_start();
   }
?>

Explanation

The above code checks whether the session started or not, if not started this will start the session in the PHP script.

Note

session_status() function only runs in PHP 5.4.0 version or above.

Updated on: 29-Jun-2020

3K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements