检查 PHP 会话是否已经启动 [英] Check if PHP session has already started
问题描述
我有一个 PHP 文件,有时从已启动会话的页面调用,有时从未启动会话的页面调用.因此,当我在此脚本上使用 session_start()
时,有时会收到会话已启动"的错误消息.为此,我放置了以下几行:
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:
注意:未定义变量:_SESSION
Notice: Undefined variable: _SESSION
有没有更好的方法来检查会话是否已经开始?
Is there a better way to check if session has already started?
如果我使用 @session_start
会使事情正常工作并关闭警告吗?
If I use @session_start
will it make things work properly and just shut up the warnings?
推荐答案
PHP >= 5.4.0 , PHP 7 版本的推荐方式
if (session_status() === PHP_SESSION_NONE) {
session_start();
}
参考:http://www.php.net/manual/en/function.session-status.php
对于 PHP < 的版本5.4.0
if(session_id() == '') {
session_start();
}
这篇关于检查 PHP 会话是否已经启动的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!