Almost every site I know creates user cookies. But unlike your website, these yummy pieces of data don’t reside in your server but on your user’s browser. So while it can contain some very sensitive data like user ids and sessions, you have limited control over it once it’s with your user.
Thankfully, there’s an easy way to fix this. Put this in your config file (or whatever PHP file first loads for your app, like an includes file).
ini_set('session.cookie_httponly', 1);
ini_set('session.cookie_secure', 1);
The HTTPOnly flag lets the browser know that only the server should be able to access the cookie. Do note that while this does prevent client scripts from accessing the cookie, the same restriction applies to your own client-side scripts. So any Javascript framework you use such as React or Vue won’t be able to use the cookie, something to consider when developing your frontend.
The second Secure flag means that cookies are only sent via HTTPS, which prevents third-parties from intercepting the cookie data. Just remember that your site needs to be HTTPS already or else browsers won’t be able to create these secure cookies.
For Laravel devs, this is actually even easier to set.
- Open
config/session.php
- Change these settings:
'secure' => true,
'http_only' => true,
These settings only apply if you created the cookie using Laravel’s own methods (aka \Cookie) and don’t apply if you made them using PHP directly (setcookie).
You can also double check your cookie security via GeekFlare. You should get a green shield if you did everything right.
Source: Stackoverflow
Learn more: developer.mozilla.org