简体   繁体   English

练习使用session_start()

[英]Practice to use session_start()

Should I use 我应该使用

session_start()

or 要么

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

because I remember correctly that without the latter there will be another error message? 因为我没有记错,没有后者,还会出现另一条错误消息?

Recommended way for versions of PHP >= 5.4.0 PHP> = 5.4.0版本的推荐方法

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

Source: http://www.php.net/manual/en/function.session-status.php 资料来源: http : //www.php.net/manual/en/function.session-status.php

For versions of PHP < 5.4.0 对于PHP <5.4.0版本

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

Both of these should work for what you are asking for. 两者都应该满足您的要求。

I do something like this to stop session hijacking. 我这样做是为了阻止会话劫持。 And then just call the function at the start of every page. 然后只需在每个页面的开头调用该函数。

public function start_session()
{
    session_start();

    if (rand(1, 10) == 5)
    {
        session_regenerate_id();
    }
}

The good practice is to always put session_start() at the very begining of your code, no matter what case your are facing. 好的做法是始终将session_start()放在代码的开头,无论遇到什么情况。

From the official PhP documentation for session_id() : 来自session_id()的官方PhP文档:

session_id() returns the session id for the current session or the empty string ("") if there is no current session (no current session id exists). session_id()返回当前会话的会话ID,如果没有当前会话(不存在当前会话ID),则返回空字符串(“”)。

Here is an example of how you could check for an already existing session_id() : 这是一个如何检查现有的session_id()的示例:

session_start();

if( empty(session_id()) ) {
    session_id();
}

Always from the documentation : 始终从文档中获取:

session_id() is used to get or set the session id for the current session. session_id()用于获取或设置当前会话的会话ID。

As the php manual states, the session_create function will create a new session or return the current session if you already created one. 如php手册所述, session_create函数将创建一个新会话,或者如果您已经创建了一个会话,返回当前会话 So there should be no need to check if there is a session or not. 因此,无需检查是否存在会话。 If you still want to check for it, i´d recommend using Flux Coders way. 如果仍然要检查,我建议使用Flux Coders方法。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM