strip_tags and htmlentities

前端 未结 4 1376
一个人的身影
一个人的身影 2020-12-05 08:49

Should I use htmlentities with strip_tags?

I am currently using strip_tags when adding to database and thinking about removing

相关标签:
4条回答
  • 2020-12-05 08:57

    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.

    0 讨论(0)
  • 2020-12-05 08:59

    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 !

    0 讨论(0)
  • 2020-12-05 09:12

    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.

    0 讨论(0)
  • 2020-12-05 09:17

    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

    0 讨论(0)
提交回复
热议问题