strip_tags not working

2019-07-20 20:39发布

问题:

I am truing to filter html characters out like this

$user = $_POST["user"]; //Get username from <form>
mysql_real_escape_string($user); //Against SQL injection
strip_tags($user); //Filter html characters out

But for some reason this is not filtering html characters out. I don't know why, could it by mysql_real_escape_string?

回答1:

...But, do you mean:

$user = $_POST["user"]; // Get username from <form>
$user = mysql_real_escape_string($user); // Against SQL injection
$user = strip_tags($user); // Filter html characters out

?

As said in the other answers (referring to strip_tags(), but it's the same for mysql_real_escape_string()), these functions do not alter strings directly, but return the modified copy. So you have to assign return values to the same (or another) variable!



回答2:

strip_tags($user); //Filter html characters out

should be replaced with this:

$user = strip_tags($user); //Filter html characters out

strip_tags returns the stripped value

See doc: http://nl2.php.net/strip_tags

This is the same with mysql_real_escape_string()

$user = mysql_real_escape_string($user); //Against SQL injection


回答3:

You are using strip_tags improperly:

string strip_tags ( string $str [, string $allowable_tags ] )

Modifying the code to assign it to a return value should fix it

$user = strip_tags($user); //Filter html characters out

EDIT

Just for completeness sakes, thanks for lorenzo-s for pointing it out, you also need to do the same to the mysql_real_escape_string

$user = mysql_real_escape_string($user); // Against SQL injection


回答4:

As already said

$user = strip_tags($user);

should be used, but I'd also put

mysql_real_escape_string($user);

AFTER the call to strip_tags();