PHP 7.2 Warning: “Cannot change session name when session is active”

前端 未结 3 538
孤城傲影
孤城傲影 2020-12-09 16:58

Since PHP on our server was upgraded to 7.2 from 7.0. I am getting the following warning (which leads to error) if a new deployment is done. The reason is probably, that old

3条回答
  •  隐瞒了意图╮
    2020-12-09 17:26

    TLDR: if the session exists, use setcookie(session_name(), session_id(), ...) else use session_set_cookie_params(...)

    https://www.php.net/manual/en/function.session-set-cookie-params.php#100657

    As PHP's Session Control does not handle session lifetimes correctly when using session_set_cookie_params(), we need to do something in order to change the session expiry time every time the user visits our site. So, here's the problem.

    
    

    This code doesn't change the lifetime of the session when the user gets back at our site or refreshes the page. The session WILL expire after $lifetime seconds, no matter how many times the user requests the page. So we just overwrite the session cookie as follows:

    
    

    And now we have the same session cookie with the lifetime set to the proper value.

    My solution:

    Originally:

            $cookieParams = session_get_cookie_params();
    
            session_set_cookie_params(
                $seconds,
                $cookieParams['path'],
                $cookieParams['domain'],
                $cookieParams['secure']
                );
    

    Now:

            if(isset($_SESSION)) {
                if ($seconds != 0) {
                    setcookie(session_name(), session_id(), time() + $seconds);
                } else {
                    setcookie(session_name(), session_id(), $seconds);
                }
            } else {
                $cookieParams = session_get_cookie_params();
    
                session_set_cookie_params(
                    $seconds,
                    $cookieParams['path'],
                    $cookieParams['domain'],
                    $cookieParams['secure']
                );
            }
    

提交回复
热议问题