The security of session handling in PHP can easily be enhanced through the use of a few configuration settings and the addition of an SSL certificate. Whilst this topic has been covered numerous times before it still bears mentioning with a large number of PHP sites and servers having not implemented these features.

To prevent session hijacking through cross site scripting (XSS) you should always filter and escape all user supplied values before printing them to screen. However some bugs may slip through or a piece of legacy code might be vulnerable so it makes sense to also make use of browser protections against XSS.

By specifying the HttpOnly flag when setting the session cookie you can tell a users browser not to expose the cookie to client side scripting such as JavaScript. This makes it harder for an attacker to hijack the session ID and masquerade as the effected user.

A helpful setting has been added to the PHP configuration to automate this process this for you.

It is also a good idea to make sure that PHP only uses cookies for sessions and disallow session ID passing as a GET parameter:

It is important to point out that HttpOnly, whilst useful as another layer in the onion of security is not going to protect a user from other forms of XSS attack. As previously mentioned on GNUCitizen session hijacking is often avoided by attackers as it requires getting and keeping a user in the right state in the target application. You must ensure that the rest of you application is not XSS vulnerable to prevent attackers utilising other vectors.

So it is just one very small step in making your PHP installation slightly more secure, but if you are not doing it then you are failing to exploit all the avenues available to you.

Another important way to increase the security of PHP sessions in your application is to install an SSL certificate on the web server and force all user interactions to occur over HTTPS only. This will prevent the users session ID from being transmitted in plain text to make it much harder to hijack the users session.

Helpfully PHP has another ini setting to assist you in ensuring session cookies are only sent over secure connections (thank you to Padraic for reminding me):

If you liked this post then you’ll probably also like 3 things I set on new servers for more security tips.