1

In my web app is a config file which includes i.e. database connection settings ans is always loaded at the first line of a PHP script. I would like to include a function which cleans all POST and GET data for maybe existing XSS and SQL Injection risks.

I am not sure if that function is really enough

function make_safe($variable) 
{
   $variable = strip_tags(mysql_real_escape_string(trim($variable)));
   return $variable; 
}

foreach ($_POST as $key => $value) {
   $_POST[$key] = make_safe($value);
}
//Same for $_GET & $_SESSION

Do you have recommendation for this problem?

Thomas1703
  • 1,152
  • 5
  • 16
  • 33
  • 3
    You have two different problems here. Focus on them one at a time. Deal with SQL injection when inserting data into SQL. Deal with XSS when inserting data into HTML. – Quentin Feb 18 '13 at 14:58
  • [How to prevent SQL injection in PHP?](http://stackoverflow.com/questions/60174/how-to-prevent-sql-injection-in-php) is a duplicate of the *first* problem you have (SQL injection). XSS is your second problem. There are plenty of answers explaining how to defend against that too, search around for them. – Quentin Feb 18 '13 at 14:59
  • If you use above mentioned function, then will you be able to use editors in your app? – Bhavik Shah Feb 18 '13 at 14:59

1 Answers1

4

This function:

function make_safe($variable) 
{
   $variable = strip_tags(mysql_real_escape_string(trim($variable)));
   return $variable; 
}

Will not work

SQL injection and XSS are two different beasts. Because they each require different escaping you need to use each escape function strip_tags and mysql_real_escape_string separatly. Joining them up will defeat the security of each.

Use the standard mysql_real_escape_string() when inputting data into the database. Use strip_tags() when querying stuff out of the database before outputting them to the screen.

Why combining the two function is dangerous From the horses mouth: http://php.net/manual/en/function.strip-tags.php

Because strip_tags() does not actually validate the HTML, partial or broken tags can result in the removal of more text/data than expected.

So by inputting malformed html into a database field a smart attacker can use your naive implementation to defeat mysql_real_escape_string() in your combo.

  • 3
    Don't use mysql_real_escape_string. Stop using the obsolete mysql extension entirely and use PDO or mysqli. – Quentin Feb 18 '13 at 15:04