如何设置会话.cookie值httponly在Codeigniter


How to set session.cookie value httponly in Codeigniter

我正在使用Codeigniter框架进行开发,我必须在我的应用程序上应用一些安全性。我希望我的cookie有httponly属性通过一些配置更改在整个应用程序中应用。我在我的应用程序/配置文件

中做了以下更改
$config['cookie_secure']    = TRUE;
$config['cookie_httponly'] = TRUE;

我已经修改了php.ini文件

ini_set( 'session.cookie_httponly', 1 );

在上面所说的更改之后,我能够看到cookie属性在我的本地服务器上更改为httponly,但是当我在live服务器上部署应用程序时,它不起作用。

httpponly cookie是支持HTTPS的网站,如https://www.samplewebsite.com,你不需要手动设置它。只需要求您的服务提供商将"cookie_httponly"值更改为true,或者如果您有服务器访问权限,请自己设置它。你也可以把下面的代码应用到你的。htaccess文件中。

Header edit Set-Cookie ^(.*)$ $1;Secure;HttpOnly
Header set Set-Cookie "%{http_cookie}e; HTTPOnly" env=http_cookie   

我也遇到过类似的问题,答案很简单。您需要修改CodeIgniter系统库system/libraries/Session.php中的一个函数,如下所示:

/**
* Write the session cookie
 *
 * @access  public
 * @return  void
 */
function _set_cookie($cookie_data = NULL)
{
    if (is_null($cookie_data))
    {
        $cookie_data = $this->userdata;
    }
    // Serialize the userdata for the cookie
    $cookie_data = $this->_serialize($cookie_data);
    if ($this->sess_encrypt_cookie == TRUE)
    {
        $cookie_data = $this->CI->encrypt->encode($cookie_data);
    }
    else
    {
        // if encryption is not used, we provide an md5 hash to prevent userside tampering
        $cookie_data = $cookie_data.md5($cookie_data.$this->encryption_key);
    }
    $expire = ($this->sess_expire_on_close === TRUE) ? 0 : $this->sess_expiration + time();
    // Set the cookie
    setcookie(
                $this->sess_cookie_name,
                $cookie_data,
                $expire,
                $this->cookie_path,
                $this->cookie_domain,
                $this->cookie_secure,
                true// <-- SYSTEM LIBRARY MODIFICATION TO SET httpOnly to true!!
            );
}

上面的函数_set_cookie()需要一个额外的参数,它将强制所有的cookie都是HTTP Only。您可以扩展此库并添加新版本的函数(推荐),但为了简单起见,我在这里只是硬编码。