PHP code to filter input against XSS/Injection attacks

Most php coded scripts are vulnerable to many hacks and mailicious code, just because many developers do not write code filtering and sanitizing user inputs, especially in forms using GET and POST.

The golden rule is “Never trust user input”.

Fortunately, it is very easy to implement the filtering mechanisms to guard against XSS and mysql injections.

1.  Simple filter function

Its  a home made  function that pretty much works effectively.

function filter($data) {
$data = trim(htmlentities(strip_tags($data)));
if (get_magic_quotes_gpc())
$data = stripslashes($data);
$data = mysql_real_escape_string($data);
return $data;
}

If you want to filter multiple POST or GET form data in an array , use this loop to filter.

foreach($_POST as $key => $value) {

$mydata[$key] = filter($value);

}

All the filtered clean data is stored in $sanitized array, which you have to pull out.

(b)  Outputting to browser: When you output anything in the browser, dont just echo it, always use htmlspecialchars() function to output data to browser. This way any/all malicious javascript  code dont get executed by you script, rather it just gets encoded.

echo htmlspecialchars(“<a href=’test’>Test</a>”, ENT_QUOTES);

//Output:  &lt;a href=&#039;test&#039;&gt;Test&lt;/a&gt;

2. Use filter_var()

As of PHP 5.2, this function makes life easy to sanitize or filter data, in a fly.

$int = filter_var(‘544’, FILTER_VALIDATE_INT);
$string = filter_var(‘<p>Hello world </p>’, FILTER_SANITIZE_STRING);
$ip = filter_var(‘192.2.3.0’, FILTER_VALIDATE_IP);
$home = filter_var($_POST[‘homepage’], FILTER_SANITIZE_URL);
$em = filter_var($_POST[’email’], FILTER_SANITIZE_EMAIL);

To filter array data, for example from $_POST use filter_var_array() function. For example if you have, name, email and url in your form, here is a simplified code.

$afilter = array(
‘name’ -> FILTER_SANITIZE_STRING,
’email’ -> FILTER_SANITIZE_EMAIL,
‘url’ -> FILTER_SANITIZE_URL
);

$sanitized = filter_var_array( $_POST, $aFilter);

3. Use Html purifier

This library pretty much handles everything from a to z. You can download html purifier and use the code like this. There is a standalone version available for this library and this requires just a single file for it to work.

The code goes like this:

[php]

$config = HTMLPurifier_Config::createDefault();
$purifier = new HTMLPurifier($config);
$clean_html = $purifier->purify($dirty);
[/php]