0

Will this function below be able to prevent XSS attacks and sql injections ?

require_once('security.class.php');
function secure_data($data) {
    $data = mysql_real_escape_string($data);
    $filtered_data = filter_var($data, FILTER_SANITIZE_STRING);
    $secure_class = new security_class();
    $clean_data = $secure_class->xss_clean($filtered_data);         
    return $clean_data;
}

The security class is from codeigniter.

hsuk
  • 6,770
  • 13
  • 50
  • 80
  • why do you think it woudln't? – Juris Malinens Feb 27 '13 at 09:16
  • 1
    Even if it does, you shouldn't use it. It uses an obsolete database api and tries to do all sanitization at input instead of Just In Time. Protection against SQL Injection should be done as the query is built. Protection against XSS should be done as the data is inserted into an HTML document. You also shouldn't use XSS protection techniques that risk throwing away real data if you can avoid them. – Quentin Feb 27 '13 at 09:17
  • [The ultimate clean/secure function](http://stackoverflow.com/questions/4223980/the-ultimate-clean-secure-function) – Your Common Sense Feb 27 '13 at 10:09

1 Answers1

6

You shouldn't be trying to "brute force" security like this - layering all of these different filters/escapes one after another on every piece of data is silly and may actually make the escaping not work as intended.

This is because the kinds of characters that are added for one kind of escaping may be removed by another. You may also end up with over-escaping.

Instead, you should use the escaping function that is specifiy for what you are actually trying to do:

  • Before you put values into a SQL query, run them through mysqli_real_escape_string() (or better yet, use prepared statements via MySQLi/PDO).
  • Before you echo values out to a HTML response, run them through HTML escaping and/or XSS cleaning.
  • Etc.
Amber
  • 507,862
  • 82
  • 626
  • 550