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

Hide Your Folders and Directories!

As a follow up to this post, you should also hide your directories. People have no business browsing the contents of your server using their browser.

The fix is quite simple for Apache:

  1. sudo nano /etc/apache2/apache2.conf
  2. Look for:
    <Directory /var/www/>
    Options Indexes FollowSymLinks
  3. Then change it to:
    <Directory /var/www/>
    Options -Indexes +FollowSymLinks
  4. sudo service apache2 restart
  5. Check your subfolders if you can browse them via the browser (you shouldn’t be able to)

Source: Vultr

Hide Your Git Directory!

It seems like one of my projects had my git repo for the entire world to see. Great if it was open sourced, but even so, it’s going to be a mess if I don’t close it up.

If you’re using Apache, this should be easy to fix:

  1. sudo nano /etc/apache2/conf-enabled/security.conf
  2. Then look for “DirectoryMatch”. Ctrl + W > type DirectoryMatch > Enter
  3. Uncomment the code and replace so that it looks like this:
    <DirectoryMatch "/\.git">
    Require all denied
    </DirectoryMatch>
  4. sudo service apache2 restart
  5. You can check if it worked by visiting your .git directory in the browser ex. https://example.com/.git/

source: David Egan