PHP security considerations

When developing a script wether if it’s in PHP or any other language you should always consider the security aspect. I’m sure the last thing you want is to get your script (and ultimately your data) hacked.

To make sure this does not happen there are a few steps you should pay attention at:

  1. Turn OFF the register_globals option
  2. Always declare variables in advance
  3. Check input type, length and format
  4. Use mysql_real_escape_string() before passing values to a MySQL query
  5. Use htmlentities() to convert characters to html entities before passing values to a MySQL query
  6. Turn OFF the error reporting and display

Here are some ways on how to achieve these:

1. To turn OFF the register_global option:

Edit your php.ini and turn it OFF or if you don’t have access to it add the following to the .htaccess file in your server:

php_flag register_globals 0

2. Always declare variables in advance:

Define default values to all the variables you’re going to use in the beginning of your script.

3. Check input type, length and format:

Always make sure that the value of the variable is exactly what the script should expect.

Checking type (example):

if ($settype($var, ‘integer’)) exit(“$var is an invalid value”);

Checking length (example):

if(strlen($var) > 20) exit (“$var has to have a maximum of 20 characters”);

Checking format (example):

$format = “^[_a-z0-9-]+(\.[_a-z0-9-]+)*@[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,3})$”;

if(!eregi($format, $email)) exit(“$email is not a valid email address”);

4. Use mysql_real_escape_string() before passing values to a MySQL query

Escape the content of your variables before passing them to a MySQL Query to sanitize the values passed to your data base:

$escaped = mysql_real_escape_string($var);

$action = “SELECT * FROM table WHERE field = ‘$escaped’ “;

5. Use htmlentities() to convert characters to html entities before passing values to a MySQL query

Another way to sanitize the values passed to your data base is by using the htmlentities() function. This converts special characters to their corresponding HTML code:

$convert= htmlentities($var);

$action = “SELECT * FROM table WHERE field = ‘$convert’ “;

6.  Turn OFF the error reporting and display

You should never allow the system to show the error messages in your live production server because these messages can provide precious information about your system.

You can either set both error_reporting and display_errors to 0 in php.ini or when you execute the scripts with error_reporting(0) and display_errors(0).


If you would like to know more about PHP Security I recommend the book “Pro PHP Security” from Chris Snyder.


Be the first to comment

Leave a Reply

Your email address will not be published.


*