Sanitize PHP Variables with OWASP PHP Filter
Jon Moffet
If you've been doing PHP programming for a while, I'm sure that you will understand the importance of filtering suspicious variable from your PHP scripts before using it for database storage or display.
This is due to security reason that somebody (or somthing) will try to perform injection attack on your web system.
Filtering PHP variables involve series of regular expression test to eliminate unwanted entities that could post a risk to your scripts.
Due to the typeless nature of PHP programming language, each of the variables need to be filtered in order to be sure that a float or integer variables would only contain numbers and not other entities, and so on.
Fortunately somebody already come out with a library that should perform the necessary tasks for you, it is called OWASP PHP Filters. The library come with built-in filtering function which is suitable for use on different data types.
To use it, you only need to include the file "sanitizept.inc.php" in your php file. For example let say that you want to sanitize a floating number that represent the amount of currency taken from a POST variable.
-
require("sanitizept.inc.php"):
-
-
$amount = $_POST['amount']:
-
$amount=sanitize($amount,SQL|FLOAT):
-
-
//any other characters beside floating numbers will be filtered out
-
echo $amount;
From here you can be sure that the $amount only contains floating numbers by filtering it using the library, the SQL flag use is to make sure that the variable entered is safe to be included in SQL query.
There are other flags and function that you can use like :
- sanitize_paranoid_string($string) -- input string, returns string stripped of all non alphanumeric
- sanitize_system_string($string) -- input string, returns string stripped of special characters
- sanitize_sql_string($string) -- input string, returns string with slashed out quotes
- sanitize_html_string($string) -- input string, returns string with html replacements for special characters
- sanitize_int($integer) -- input integer, returns ONLY the integer (no extraneous characters
- sanitize_float($float) -- input float, returns ONLY the float (no extraneous characters)
- fsanitize_email($string) -- filter email string
- fsanitize_ip($string) -- filter ip addresses
You can download OWASP PHP Filters here to start using it in your own php code.
Tags: php, security, owasp, php filters, filters, sanitize, injection, sql injection
Posted in Uncategorized |








May 16th, 2007 at 7:19 pm
[...] it is prudent to safeguard your web application by filtering unsafe input variables before inputting them into SQL [...]
October 15th, 2010 at 4:34 am
Nice info. Here is a similar article but using a popular CakePHP class:
http://website-security.info/sanitize-php-variables