简体   繁体   中英

strip_tags and htmlentities

Should I use htmlentities with strip_tags ?

I am currently using strip_tags when adding to database and thinking about removing htmlentities on output; I want to avoid unnecessary processing while generating HTML on the server.

Is it safe to use only strip_tags without allowed tags?

First: Use the escaping method only as soon as you need it. Ie if you insert something into a database, only escape it for the database, ie 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. Ie 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.

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 &amp; b"
"<b>foo</b>" --> "&lt;b&gt;foo&lt;/b&gt;"

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

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.

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 !

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM