Check if PHP session has already started
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?
Recommended way for versions of PHP >= 5.4.0
if (session_status() == PHP_SESSION_NONE) {
session_start();
}
Source: http://www.php.net/manual/en/function.session-status.php
For versions of PHP < 5.4.0
if(session_id() == '') {
session_start();
}
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.
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
链接地址: http://www.djcxy.com/p/9902.html
上一篇: Newbe PHP:我在运行简单的示例代码时遇到了麻烦
下一篇: 检查PHP会话是否已经开始