Should I use htmlentities
with strip_tags
?
I am currently using strip_tags
when adding to database and thinking about removing
First: Use the escaping method only as soon as you need it. I.e. if you insert something into a database, only escape it for the database, i.e. apply mysql_real_escape_string (or PDO->quote
or whatever database layer you are using). But don't yet apply any escaping for the output. No strip_tags
or similar yet. This is because you may want to use the data stored in the database someplace else, where HTML escaping isn't necessary, but only makes the text ugly.
Second: You should not use strip_tags
. It removes the tags altogether. I.e. the user doesn't get the same output as he typed in. Instead use htmlspecialchars. It will give the user the same output, but will make it harmless.
try this one and see the differences:
<?php
$d= isset($argv[1]) ? $argv[1] : "empty argv[1]".PHP_EOL;
echo strip_tags(htmlentities($d)) . PHP_EOL;
echo htmlentities(strip_tags($d)) . PHP_EOL;
?>
open up cmd or your terminal and type something like following;
php your_script.php "<br>foo</br>"
this should get what you want and safe !
I wouldn't use htmlentities
as this will allow you to insert the string, as is, into the database. Yhis is no good for account details or forums.
Use mysql_real_escape_string
for inserting data into the database, and strip_tags
for receiving data from the database and echoing out to the screen.
strip_tags
will remove all HTML tags:
"<b>foo</b><i>bar</i>" --> "foobar"
htmlentities
will encode characters which are special characters in HTML
"a & b" --> "a & b"
"<b>foo</b>" --> "<b>foo</b>"
If you use htmlentities
, then when you output the string to the browser, the user should see the text as they entered it, not as HTML
echo htmlentities("<b>foo</b>");
Visually results in: <b>foo</b>
echo strip_tags("<b>foo</b>");
Results in: foo