How do you set up use HttpOnly cookies in PHP

后端 未结 10 1767
终归单人心
终归单人心 2020-12-04 07:09

How can I set the cookies in my PHP apps as HttpOnly cookies?

相关标签:
10条回答
  • 2020-12-04 07:14

    You can use this in a header file.

    // setup session enviroment
    ini_set('session.cookie_httponly',1);
    ini_set('session.use_only_cookies',1);
    

    This way all future session cookies will use httponly.

    • Updated.
    0 讨论(0)
  • 2020-12-04 07:24

    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)
  • 2020-12-04 07:27

    Explanation here from Ilia... 5.2 only though

    httpOnly cookie flag support in PHP 5.2

    As stated in that article, you can set the header yourself in previous versions of PHP

    header("Set-Cookie: hidden=value; httpOnly");
    
    0 讨论(0)
  • 2020-12-04 07:30
    • For your cookies, see this answer.
    • For PHP's own session cookie (PHPSESSID, by default), see @richie's answer

    The setcookie() and setrawcookie() functions, introduced the httponly parameter, back in the dark ages of PHP 5.2.0, making this nice and easy. Simply set the 7th parameter to true, as per the syntax

    Function syntax simplified for brevity

    setcookie(    $name, $value, $expire, $path, $domain, $secure, $httponly )
    setrawcookie( $name, $value, $expire, $path, $domain, $secure, $httponly )
    

    Enter NULL for parameters you wish to remain as default. You may also want to consider if you should be setting the secure parameter.

    It is also possible using the older, lower-level header() function:

    header( "Set-Cookie: name=value; httpOnly" );
    
    0 讨论(0)
  • 2020-12-04 07:30

    You can specify it in the set cookie function see the php manual

    setcookie('Foo','Bar',0,'/', 'www.sample.com'  , FALSE, TRUE);
    
    0 讨论(0)
  • 2020-12-04 07:34

    Note that PHP session cookies don't use httponly by default.

    To do that:

    $sess_name = session_name();
    if (session_start()) {
        setcookie($sess_name, session_id(), null, '/', null, null, true);
    }
    

    A couple of items of note here:

    • You have to call session_name() before session_start()
    • This also sets the default path to '/', which is necessary for Opera but which PHP session cookies don't do by default either.
    0 讨论(0)
提交回复
热议问题