简体   繁体   中英

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

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();
}

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.

From the official PhP documentation for session_id() :

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).

Here is an example of how you could check for an already existing 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.

As the php manual states, the session_create function will create a new session or return the current session if you already created one. 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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