Security in PHP

PHP itself is neither secure nor insecure. The security of your web applications is entirely determined by the code you write. For example, if a script opens a file whose name is passed to the script as a form parameter, that script could be given a remote URL, an absolute pathname, or even a relative path, allowing it to open a file outside the site’s document root. This could expose your password file or other sensitive information

Filter Input

There are a few best practices regarding the filtering process:

  • Use a whitelist approach. This means you err on the side of caution and assume data to be invalid unless you can prove it to be valid.
  • Never correct invalid data. History has proven that attempts to correct invalid data often result in security vulnerabilities due to errors.
  • Use a naming convention to help distinguish between filtered and tainted data. Filtering is useless if you can’t reliably determine whether something has been filtered.

Example of filter input

form.html

<form action="process.php" method="POST">
 <p>Please select a color:
 <select name="color">
 <option value="red">red</option>
 <option value="green">green</option>
 <option value="blue">blue</option>
 </select>
 <input type="submit" /></p>
</form>

process.php

$clean = array();
switch($_POST['color']) {
 case 'red':
 case 'green':
 case 'blue':
 $clean['color'] = $_POST['color'];
 break;
 default:
 /* ERROR */
 break;
}

Leave a Comment