Check if PHP session has already started

2018-12-31 05:42发布

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?

25条回答
美炸的是我
2楼-- · 2018-12-31 06:22
if (version_compare(phpversion(), '5.4.0', '<')) {
     if(session_id() == '') {
        session_start();
     }
 }
 else
 {
    if (session_status() == PHP_SESSION_NONE) {
        session_start();
    }
 }
查看更多
零度萤火
3楼-- · 2018-12-31 06:22

For all php version

if ((function_exists('session_status') 
  && session_status() !== PHP_SESSION_ACTIVE) || !session_id()) {
  session_start();
}
查看更多
千与千寻千般痛.
4楼-- · 2018-12-31 06:22

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.

查看更多
美炸的是我
5楼-- · 2018-12-31 06:26

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');};
查看更多
步步皆殇っ
6楼-- · 2018-12-31 06:28

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

查看更多
公子世无双
7楼-- · 2018-12-31 06:29

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";
}
查看更多
登录 后发表回答