Set httpOnly and secure on PHPSESSID cookie in PHP

前端 未结 8 1297
鱼传尺愫
鱼传尺愫 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:19

    For a WordPress website, I fixed it using the following PHP code:

    add_action('init', 'start_session', 1);
    function start_session() {
        if(!session_id()) {
            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
            );
        }
    }
    
    add_action('wp_logout','end_session');
    add_action('wp_login','end_session');
    function end_session() {
        session_destroy();
    }
    

    Paste the code in the functions.php file.

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

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

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

    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

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

    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 ]]]] )
    
    0 讨论(0)
  • 2020-12-03 10:36

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

    php_value session.cookie_httponly 1
    
    0 讨论(0)
  • 2020-12-03 10:41
    ini_set('session.cookie_httponly', 1);
    

    more information here on the PHP docs

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