how to set secure flag on cookies in laravel

30,921

Solution 1

You need to override the default setting using session_set_cookie_params, set the $secure flag to true,

void session_set_cookie_params ( int $lifetime [, string $path [, string $domain [, bool $secure = false [, bool $httponly = false ]]]] )

more info at php.net

In laravel you need to alter the config/session.php configuration,set the secure flag to true

/*
|--------------------------------------------------------------------------
| HTTPS Only Cookies
|--------------------------------------------------------------------------
|
| By setting this option to true, session cookies will only be sent back
| to the server if the browser has a HTTPS connection. This will keep
| the cookie from being sent to you if it can not be done securely.
|
*/

'secure' => true,

In newer versions of laravel you can simply set the SESSION_SECURE_COOKIE=true in the .env file

Solution 2

You can set the value of secure true in your config/session.php file as illustrated below;

'secure' => env( 'SESSION_SECURE_COOKIE', true ),
Share:
30,921

Related videos on Youtube

Keshav Kothari
Author by

Keshav Kothari

Updated on April 09, 2021

Comments

  • Keshav Kothari
    Keshav Kothari about 3 years

    I want to set secure flag for cookies data when accessing content over HTTPS.

    The cookies is used on entire application so need to global configuration to secure all the cookies.

    • madalinivascu
      madalinivascu over 6 years
      what do you mean by secure flag?
    • Keshav Kothari
      Keshav Kothari over 6 years
      While in Core PHP when creating a cookie their is one parameter of secure which make the cookie secure. If the cookies is not secure then it is not encrypted.
  • JamesRat
    JamesRat over 3 years
    That line in the config file looks like this in newer versions of Laravel: 'secure' => env( 'SESSION_SECURE_COOKIE', true ),
  • w5m
    w5m about 2 years
    This line of code may not actually set secure to true, if the .env file contains SESSION_SECURE_COOKIE=false. The second parameter passed to the env helper method simply sets the default to true and is used only if the SESSION_SECURE_COOKIE environment variable doesn't exist in the .env file.