k10gaurav
k10gaurav

Reputation: 462

How to set session.cookie value httponly in Codeigniter

I am using Codeigniter framework for the development and I have to apply some security on my application. I want my cookies to have httponly attribute to be applied throughout the application via some config changes. I have done following changes in my application/config file

$config['cookie_secure']    = TRUE;
$config['cookie_httponly'] = TRUE;

I have set changes for my php.ini file

ini_set( 'session.cookie_httponly', 1 );

After above said changes I am able to see cookie attributes are changed to httponly on my local server but when I deployed the application on live server, it doesn't worked. I am unable to understand what additional changes I need to apply.

Upvotes: 2

Views: 5330

Answers (2)

siya
siya

Reputation: 58

httpponly cookies are supported by https enabled sites like https://www.samplewebsite.com and you don't need to set it manually. Just ask your service provider to change the "cookie_httponly" value to be true or if you have server access, set it yourself. You can also apply below code to your .htaccess file.

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

Upvotes: 3

Donal.Lynch.Msc
Donal.Lynch.Msc

Reputation: 3615

I had a similar problem here and the answer is fairly straight forward. You need to modify one function in one of the CodeIgniter system libraries, system/libraries/Session.php, as follows:

/**
* 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!!
            );
}

The above function called _set_cookie() needs one additional parameter which will force the all cookies to be HTTP Only. You could probably extend this library and add the new version of the function (recommended) but I have just hard-coded it here for simplicity.

Upvotes: 0

Related Questions