Check if PHP session has already started

PhpSessionSession Variables

Php Problem Overview


I have a PHP file that is sometimes called from a page that has started a session and sometimes from a page that doesn't have session started. Therefore when I have session_start() on this script I sometimes get the error message for "session already started". For that I've put these lines:

if(!isset($_COOKIE["PHPSESSID"]))
{
  session_start();
}

but this time I got this warning message:

> Notice: Undefined variable: _SESSION

Is there a better way to check if session has already started?

If I use @session_start will it make things work properly and just shut up the warnings?

Php Solutions


Solution 1 - Php

Recommended way for versions of PHP >= 5.4.0 , PHP 7, PHP 8

if (session_status() === PHP_SESSION_NONE) {
    session_start();
}

Reference: http://www.php.net/manual/en/function.session-status.php

For versions of PHP < 5.4.0

if(session_id() == '') {
    session_start();
}

Solution 2 - Php

For versions of PHP prior to PHP 5.4.0:

if(session_id() == '') {
    // session isn't started
}

Though, IMHO, you should really think about refactoring your session management code if you don't know whether or not a session is started...

That said, my opinion is subjective, and there are situations (examples of which are described in the comments below) where it may not be possible to know if the session is started.

Solution 3 - Php

PHP 5.4 introduced session_status(), which is more reliable than relying on session_id().

Consider the following snippet:

session_id('test');
var_export(session_id() != ''); // true, but session is still not started!
var_export(session_status() == PHP_SESSION_ACTIVE); // false

So, to check whether a session is started, the recommended way in PHP 5.4 is now:

session_status() == PHP_SESSION_ACTIVE

Solution 4 - Php

you can do this, and it's really easy.

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

Solution 5 - Php

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

Solution 6 - Php

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

Consider:

var_dump($_SESSION); // null
session_start();
var_dump($_SESSION); // array
session_destroy();
var_dump($_SESSION); // array, but session isn't active.

Or:

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.

So, prior to PHP 5.4 you should set a global boolean.

Solution 7 - Php

For all php version

if ((function_exists('session_status') 
  && session_status() !== PHP_SESSION_ACTIVE) || !session_id()) {
  session_start();
}

Solution 8 - Php

Check this :

<?php
/**
* @return bool
*/
function is_session_started()
{
    if ( php_sapi_name() !== 'cli' ) {
        if ( version_compare(phpversion(), '5.4.0', '>=') ) {
            return session_status() === PHP_SESSION_ACTIVE ? TRUE : FALSE;
        } else {
            return session_id() === '' ? FALSE : TRUE;
        }
    }
    return FALSE;
}

// Example
if ( is_session_started() === FALSE ) session_start();
?>

Source [http://php.net][1] [1]: http://php.net/manual/en/function.session-status.php

Solution 9 - Php

Use session_id(), it returns an empty string if not set. It's more reliable than checking the $_COOKIE.

if (strlen(session_id()) < 1) {
    session_start();
}

Solution 10 - Php

if (session_id() === "") { session_start(); }

hope it helps !

Solution 11 - Php

This should work for all PHP versions. It determines the PHP version, then checks to see if the session is started based on the PHP version. Then if the session is not started it starts it.

function start_session() {
  if(version_compare(phpversion(), "5.4.0") != -1){
    if (session_status() == PHP_SESSION_NONE) {
      session_start();
    }
  } else {
    if(session_id() == '') {
      session_start();
    }
  }
}

Solution 12 - Php

The only thing you need to do is:

<?php
if(!isset($_SESSION))
{
session_start();
}
?>

Solution 13 - Php

Not sure about efficiency of such solution, but this is from working project This is also used if you need to define the default language

   /**
    * Start session
    * Fall back to ukrainian language
    */
   function valid_session() {
   	if(session_id()=='') {
   		session_start();
   		$_SESSION['lang']='uk';
   		$_SESSION['lang_id']=3;
   	}
   	return true;
  }

Solution 14 - Php

@ before a function call suppresses any errors that may be reported during the function call.

Adding a @ before session_start tells PHP to avoid printing error messages.

For example:

Using session_start() after you've already printed something to the browser results in an error so PHP will display something like "headers cannot be sent: started at (line 12)", @session_start() will still fail in this case, but the error message is not printed on screen.

Before including the files or redirecting to new page use the exit() function, otherwise it will give an error.

This code can be used in all cases:


    <?php 
        if (session_status() !== PHP_SESSION_ACTIVE || session_id() === ""){
            session_start(); 
        }
    ?>

Solution 15 - Php

On PHP 5.3 this works for me:

if(!strlen(session_id())){
    session_name('someSpecialName');
    session_start();
} 

then you have. If you do not put the not at if statement beginning the session will start any way I do not why.

Solution 16 - Php

Response BASED on @Meliza Ramos Response(see first response) and http://php.net/manual/en/function.phpversion.php ,

ACTIONS:

  • define PHP_VERSION_ID if not exist
  • define function to check version based on PHP_VERSION_ID
  • define function to openSession() secure

only use openSession()

    // PHP_VERSION_ID is available as of PHP 5.2.7, if our
	// version is lower than that, then emulate it
	if (!defined('PHP_VERSION_ID')) {
		$version = explode('.', PHP_VERSION);

		define('PHP_VERSION_ID', ($version[0] * 10000 + $version[1] * 100 + $version[2]));


		// PHP_VERSION_ID is defined as a number, where the higher the number
		// is, the newer a PHP version is used. It's defined as used in the above
		// expression:
		//
		// $version_id = $major_version * 10000 + $minor_version * 100 + $release_version;
		//
		// Now with PHP_VERSION_ID we can check for features this PHP version
		// may have, this doesn't require to use version_compare() everytime
		// you check if the current PHP version may not support a feature.
		//
		// For example, we may here define the PHP_VERSION_* constants thats
		// not available in versions prior to 5.2.7

		if (PHP_VERSION_ID < 50207) {
			define('PHP_MAJOR_VERSION',   $version[0]);
			define('PHP_MINOR_VERSION',   $version[1]);
			define('PHP_RELEASE_VERSION', $version[2]);

			// and so on, ...
		}
	}

	function phpVersionAtLeast($strVersion = '0.0.0')
	{
		$version = explode('.', $strVersion);

		$questionVer = $version[0] * 10000 + $version[1] * 100 + $version[2];

		if(PHP_VERSION_ID >= $questionVer)
			return true;
		else
			return false;

	}

	function openSession()
	{
		if(phpVersionAtLeast('5.4.0'))
		{
			if(session_status()==PHP_SESSION_NONE)
				session_start();
		}
		else // under 5.4.0
		{
			if(session_id() == '')
				session_start();
		}
	}

Solution 17 - Php

if (version_compare(PHP_VERSION, "5.4.0") >= 0) {
	$sess = session_status();
	if ($sess == PHP_SESSION_NONE) {
		session_start();
	}
} else {
	if (!$_SESSION) {
		session_start();
	}
}

Actually, it is now too late to explain it here anyway as its been solved. This was a .inc file of one of my projects where you configure a menu for a restaurant by selecting a dish and remove/add or change the order. The server I was working at did not had the actual version so I made it more flexible. It's up to the authors wish to use and try it out.

Solution 18 - Php

Is this code snippet work for you?

if (!count($_SESSION)>0) {
    session_start();
}

Solution 19 - Php

This is what I use to determine if a session has started. By using empty and isset as follows:

if (empty($_SESSION)  && !isset($_SESSION))  {
    session_start();
}

Solution 20 - Php

You should reorganize your code so that you call session_start() exactly once per page execution.

Solution 21 - Php

PHP_VERSION_ID is available as of PHP 5.2.7, so check this first and if necessary , create it. session_status is available as of PHP 5.4 , so we have to check this too:

if (!defined('PHP_VERSION_ID')) {
    $version = explode('.', PHP_VERSION);
    define('PHP_VERSION_ID', ($version[0] * 10000 + $version[1] * 100 + $version[2]));
}else{
    $version = PHP_VERSION_ID;
}
if($version < 50400){
    if(session_id() == '') {
        session_start();
    }
}else{
    if (session_status() !== PHP_SESSION_ACTIVE) {
        session_start();
    }
}

Solution 22 - Php

Based on my practice, before accessing the $_SESSION[] you need to call session_start every time to use the script. See the link below for manual.

http://php.net/manual/en/function.session-start.php

For me at least session_start is confusing as a name. A session_load can be more clear.

Solution 23 - Php

i ended up with double check of status. php 5.4+

if(session_status() !== PHP_SESSION_ACTIVE){session_start();};
if(session_status() !== PHP_SESSION_ACTIVE){die('session start failed');};

Solution 24 - Php

session_start();
if(!empty($_SESSION['user']))
{	  
  //code;
}
else
{
    header("location:index.php");
}

Solution 25 - Php

You can use the following solution to check if a PHP session has already started:

if(session_id()== '')
{
   echo"Session isn't Start";
}
else
{
    echo"Session Started";
}

Solution 26 - Php

Replace session_start(); with:

if (!isset($a)) {
    a = False;
    if ($a == TRUE) {
        session_start();
        $a = TRUE;
    }
}

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionLoganView Question on Stackoverflow
Solution 1 - PhplovelyramosView Answer on Stackoverflow
Solution 2 - PhpAlexView Answer on Stackoverflow
Solution 3 - PhpBenMorelView Answer on Stackoverflow
Solution 4 - PhpmiyuruView Answer on Stackoverflow
Solution 5 - Phpk.bonView Answer on Stackoverflow
Solution 6 - Phpy oView Answer on Stackoverflow
Solution 7 - PhpsupersuphotView Answer on Stackoverflow
Solution 8 - PhpElshanView Answer on Stackoverflow
Solution 9 - PhpWesley van OpdorpView Answer on Stackoverflow
Solution 10 - PhpMahesh CheliyaView Answer on Stackoverflow
Solution 11 - PhpDustin PoissantView Answer on Stackoverflow
Solution 12 - Phpuser3140580View Answer on Stackoverflow
Solution 13 - PhpAlex KhimichView Answer on Stackoverflow
Solution 14 - Phpsangram desaiView Answer on Stackoverflow
Solution 15 - PhpLucas M. OliveiraView Answer on Stackoverflow
Solution 16 - Phpuser1817927View Answer on Stackoverflow
Solution 17 - PhpThieliciousView Answer on Stackoverflow
Solution 18 - PhpNiroshanJView Answer on Stackoverflow
Solution 19 - PhpRotimiView Answer on Stackoverflow
Solution 20 - PhpSamTView Answer on Stackoverflow
Solution 21 - PhpChristian KruseView Answer on Stackoverflow
Solution 22 - PhpEduard HasanajView Answer on Stackoverflow
Solution 23 - PhpLeo TahkView Answer on Stackoverflow
Solution 24 - PhpSukanya SukuView Answer on Stackoverflow
Solution 25 - PhpManjeet Kumar NaiView Answer on Stackoverflow
Solution 26 - PhpHarshit ChaturvediView Answer on Stackoverflow