What else should I be doing to sanitize user input

2019-06-23 18:05发布

问题:

Recently, I had an audit run on some of my sites by a client. One of the things they came back with was that I could be sanitizing the input data a little better as people could still cause potential harm to the database.

The function below is what I am currently using (a leftover from the old developer) but I cannot see where the potential issue may lie.

The string that gets passed through to the database will be displayed via XML which in turn is read by a Flash application.

Could anyone tell me what I might be missing? Thanks

function secure_string($string)
{   
    return (strip_tags(addslashes(mysql_real_escape_string(
                      stripslashes($string)))));
}

回答1:

Better use the new PHP function filter_var() for cleaning input. New and better.



回答2:

It looks like there's too much going on in that function. mysql_real_escape_string() already escapes everything you need to escape, so there's no need to run addslashes() on that. In fact, it could do more harm than good by escaping the backslashes mysql_real_escape_string() creates.



回答3:

mysql_real_escape_string is the last step, you shouldn't use it your application logic. It's sole purpose is to pass strings to the database, so use it only when constructing queries. You can pass anything to mysql_real_escape_string and it will make sure you can safely store it in the database.

For the rest, it depends what do you want. If you want to strip tags, use strip_tags, etc.



回答4:

Depends on where the "secured" string will be used. If it's going to be used in the database, you only need mysql_real_escape_string(), nothing more. If it's going to be displayed in html, you only need htmlentities(), nothing more. In short: your code is doing way too much, which could even be harmful.

If you want to store it in the database for displaying it in html lateron (like a comment, for example), you should be using mysql_real_escape_string() when storing the string and htmlentities() when displaying it.



回答5:

If your server uses php 5.2 or better, you should use filter_var for the XML part.

$output = filter_var($input, FILTER_SANITIZE_STRING);

To store something into your database, use PDO and parameterized queries.



回答6:

It's a misnomer to try and fix the problem at input time, since the problem happens at output time. See my answer over here:

What’s the best method for sanitizing user input with PHP?