Set httpOnly and secure on PHPSESSID cookie in PHP

前端 未结 8 1298
鱼传尺愫
鱼传尺愫 2020-12-03 10:09

Whats the recommended way to set httponly and secure flags on the PHPSESSID cookie?

I found http://www.php.net/manual/en/session.configuration.php#ini.session.cookie

相关标签:
8条回答
  • 2020-12-03 10:43

    I was unable to get the secure flag working with session_set_cookie_params(...), so what I did was, after session_start() set the PHPSESSID cookie, I reset it with setcookie(...). The final parameter, true, makes the cookie have a secure flag.

    <?php  
    session_start();  
    $currentCookieParams = session_get_cookie_params();  
    $sidvalue = session_id();  
    setcookie(  
        'PHPSESSID',//name  
        $sidvalue,//value  
        0,//expires at end of session  
        $currentCookieParams['path'],//path  
        $currentCookieParams['domain'],//domain  
        true //secure  
    );  
    ?>
    

    When I checked the PHPSESSID cookie in Firefox, its 'Send for' property was set to 'Encrypted connections only' and its 'Expires' property was set to 'At end of session'.

    0 讨论(0)
  • 2020-12-03 10:44

    A more elegant solution since PHP >=7.0

    session_start(['cookie_lifetime' => 43200,'cookie_secure' => true,'cookie_httponly' => true]);
    

    session_start

    session_start options

    0 讨论(0)
提交回复
热议问题