仅在会话不存在时才加载session

仅在会话不存在时才加载session

本文介绍了仅在会话不存在时才加载session_start()吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否有一个简短的代码技巧来检查会话是否已开始,如果没有,则加载一个会话?当前,无论是否进行检查,如果我插入会话开始,我都会收到错误消息会话已开始...".

is there a short code trick to check if a session has started and if not then load one? Currently I receive an error "session already started..." if I put in a session start regardless of checking.

推荐答案

isset通常是检查当前是否定义了预定义变量的正确方法:

isset is generally the proper way to check if predefined variables are currently defined:

如果您使用的是5.4之前的php版本

您通常可以通过下面的代码来摆脱它的诱惑,但是要注意,如果由于某种原因禁用了会话,session_start()仍然会被调用,这可能导致错误和不必要的调试,因为$ _SESSION数组不允许创建.

you can usually get away with and its tempting just doing the code below, but be aware that if for some reason sessions are disabled, session_start() will still be called which could end up leading to errors and needless debugging since the $_SESSION array isn't allowed to be created.

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

如果您要考虑检查会话是否由于某种原因而被禁用,则可以阻止该错误消息,设置一个测试会话变量,然后验证它是否已设置.如果不是,则可以在响应中编写禁用会话的代码.您需要在脚本开始时或在脚本开始时执行所有这些操作.因此,以一个示例为例(根据错误处理设置的不同,其工作方式也不同):

if you want to account for checking to see if sessions are disabled for some reason, you can supress the error message, set a test session variable, and then verify it was set. If its not, you can code in a reaction for disabled sessions. You'll want to do all this at or near the start of your script. So as an example(works differently depending on error handling setting):

if(!isset($_SESSION)){session_start();}
$_SESSION['valid'] = 'valid';
if($_SESSION['valid'] != 'valid')
{
   //handle disabled sessions
}

但是,如果您使用的是5.4或更高版本的php

您可以使用 session_status()函数,这是一个更好的选择,因为它可以解决会话问题被禁用,并检查会话是否已经存在.

You can use the session_status() function, a better option as it accounts for sessions being disabled and checks if a session already exists.

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

请注意, PHP_SESSION_NONE 是PHP设置的常量,因此不需要用引号引起来.它的计算结果为整数1,但它是专门为消除幻数而设置的常数,最好针对该常数进行测试.

NOTE that PHP_SESSION_NONE is a constant set by PHP and therefore does not need to be wrapped in quotes. It evaluates to integer 1, but as its a constant that was specifically set to eliminate the need for magic numbers, best to test against the constant.

这篇关于仅在会话不存在时才加载session_start()吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-03 21:47