Securing Site Cookies in PHP

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.

  1. Open config/session.php
  2. 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

How useful was this post?

Click on a star to rate it!

Average rating 0 / 5. Vote count: 0

No votes so far! Be the first to rate this post.

As you found this post useful...

Follow us on social media!

We are sorry that this post was not useful for you!

Let us improve this post!

Tell us how we can improve this post?

Glenn Santos

Published by Glenn Santos

Leave a Reply