Set httpOnly and secure on PHPSESSID cookie in PHP

2019-01-18 02:00发布

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-httponly. Any better suggestions?

thanks

6条回答
乱世女痞
2楼-- · 2019-01-18 02:14

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

查看更多
虎瘦雄心在
3楼-- · 2019-01-18 02:18

Using .htaccess for this purpose just slows down your application.

I think its better to add this snippet in your main config file ( example config.php ) or main include file ( example global.php )

    // Prevents javascript XSS attacks aimed to steal the session ID
    ini_set('session.cookie_httponly', 1);

    // Prevent Session ID from being passed through  URLs
    ini_set('session.use_only_cookies', 1);

If you are using https:// instead of http:// , then also do

     // Uses a secure connection (HTTPS) 
     ini_set('session.cookie_secure', 1); 

This method is also suitable for thos who dont have access to php.ini

查看更多
爷的心禁止访问
4楼-- · 2019-01-18 02:27

In my opinion the best would be: http://www.php.net/manual/en/function.session-set-cookie-params.php

void session_set_cookie_params ( int $lifetime [, string $path [, string $domain [, bool $secure = false [, bool $httponly = false ]]]] )
查看更多
smile是对你的礼貌
5楼-- · 2019-01-18 02:30
ini_set('session.cookie_httponly', 1);

more information here on the PHP docs

查看更多
成全新的幸福
6楼-- · 2019-01-18 02:32

I use Apache httpd over HTTPS, set session.cookie_httponly = 1 & session.cookie_secure = 1 works for me.

查看更多
时光不老,我们不散
7楼-- · 2019-01-18 02:35

If you are using Apache, try this on your .htaccess

php_value session.cookie_httponly 1
查看更多
登录 后发表回答