Reputation: 18511
Is there a difference where I place my strip_tags
and htmlspecialchars
tag's? I read that Example 2 is better than Example 1.
But I don't understand how that can be the case, aren't these the same thing? I don't know if it also makes a difference that I am setting it back into a $_POST[]
variable.
In my case, it's much easier to use Example 1, because no matter where I use $_POST['test']
, I know it's safe... while I need to find ever instance that I echo $_POST['test']
and put the tags around it for Example 2.
Is one truly version safer against XSS Leaks?
Example 1:
<?php
$_POST['test'] = htmlspecialchars(strip_tags($_POST['test']));
// other code
<form action="" method="POST">
<input type="hidden" name="test" value="<?=$_POST['test']?>" />
</form>
?>
Example 2:
<?php
// other code
<form action="" method="POST">
<input type="hidden" name="test" value="<?=htmlspecialchars(strip_tags($_POST['test']))?>" />
</form>
?>
Upvotes: 2
Views: 10347
Reputation: 19
I use it like this
$this->message = htmlspecialchars(strip_tags($this->message));
Upvotes: 1
Reputation: 11
This part of code prevent XSS perfectly.
<?php
$myVar = htmlspecialchars($_POST['test']);
// other code
<form action="" method="POST">
<input type="hidden" name="test" value="<?php echo $myVar; ?>" />
</form>
?>
Upvotes: 1
Reputation: 29424
Both examples are equal (in output).
The problem I can see is that example #1 overwrites the $_POST
data.
I would advise against doing so because you cannot restore the original data at a later point in the script (e.g. if you wish to save the data into a database or output it in a non-HTML context).
They are two different functions.
In your case you should only use htmlspecialchars()
since this function is meant to escape special HTML characters (<, >, "
).
strip_tags()
on the contrary strips HTML tags (and some other stuff, see the docs). Do you really want this behavior? I doubt that. Stripping HTML tags differs from escaping them insofar that it really removes the tags. Escaping only "escapes" them so that the browser renders them as normal text.
Upvotes: 3
Reputation: 744
If you have to use $_POST['test'] in multiple spots I would use example 1 since you wont have to process the other functions (strip_tags, htmlspecialchars) over again sanitizing the same data you already have.
Upvotes: 0