Security in PHP

2010-08-16

Here are some tips to strengthen the security of a PHP application. Some are written from personal experience and some are tips I got from friends. There will probably be a sequel to this article.

Remote File Inclusion

In PHP there are several features to include code from other files. The files that might be included should be carefully monitored and should never be selected based on a user’s input. If done carelessly, chances are that someone includes their own code from another page that could potentially damage your website.

SQL Injections

If your PHP application is connected to a database and receive information by the user, it may be a risk of SQL injection if you do not protect against this. At low levels of protection, a vicious individual can use this weakness to send database code to the server and execute it in order to retrieve user information or to delete data. There are, among many others, a couple of functions that can be used to deal with this problem. One is these functions, mysql_real_escape_string(), encodes some special characters so that text can only be handled as text and not as code. The second function in this article is is_numeric() that checks if a variable contains only digits or not. In many cases you want to retrieve information from a database from a given ID number. The function can then be used to verify that the given ID number contains only numbers. Examples of both functions are below:

<?php
$text = mysql_real_escape_string($_POST['text']);

if(is_numeric($_GET['id'])){
    echo("ID contains only numbers.");
}
?>

Input from visitors

It may be useful to verify all data that the visitor sends to your page. Both to ensure that it is formatted correctly and is of the correct type, and to verify that it does not contain any malicious code. PHP has several built-in functions to control text, including htmlentities() that translates all the HTML code to characters so everything is printed without formatting. Another useful feature is the preg_match() which controls the format of a text string. There are examples of both features below:

<?php
$text = htmlentities($_POST['text']);

if(preg_match('/name/', $_POST['text'])){
    echo("The text contains 'name'.");
}
?>

Save passwords as hashes

When you store passwords, it may be appropriate to store them as a hash. A hash is a one way encryption which means that you can not decipher it. If a person would get access the database or file where the passwords are stored, hashing may impair or may even prevent the person from viewing the passwords. Some common hash algorithms are MD5 and SHA1  where SHA1 is a little better.

<?php
$password = "secret_password";
$hash_md5 = md5($password);
$hash_sha1 = sha1($password);
?>

You can try to generate various hashes on this page.