coolpup
coolpup

Reputation: 159

htmlentities and htmlspecialchars stops text from displaying

I'm trying to display comments from a comment box form on my website. I originally displayed it by using:

<?php while($comment_text = mysqli_fetch_assoc($display_comments)) { ?>
<div class="comment" style="margin-bottom: 2em;">
    <div class="author">
      <b><?php echo htmlentities($comment_text["author"]); ?></b>
    <span class="datetime">
      <i><?php echo datetime_to_text($comment_text["created"]); ?></i>
    </span>
    </div>
  <div class="body">
        <?php echo strip_tags($comment_text["body"], '<strong><em><p>'); ?>
  </div>
</div>
<?php } ?> 

Where I use "strip_tags" when the "body" text is displayed. However, I heard I should be using htmlentities or htmlspecialchars instead as it's safer, but whenever I try replacing "strip_tags" with one of them, the comment doesn't display. It just shows the comment's author and then nothing below it.

The form is working properly though, and I use "mysqli_real_escape_string" whenever I post to my database. I see the comments in the database, they just won't display when I use htmlentities or htmlspecialchars.

I'm pretty new at php, and I want to make sure my form is safe. Any help would be appreciated!

UPDATE: I've tried displaying different test comments. Nothing will show up when I use htmlspecialchars, even if it's something simple like "test"

Upvotes: 1

Views: 463

Answers (1)

jeroen
jeroen

Reputation: 91744

You will have to choose what you want to use: Either you allow some html tags and you cannot use htmlspecialchars or you use htmlspecialchars and do not allow any html.

Note that the first option has a risk of xss so you should not use it if the content is not trusted.

The problem is that when you use htmlspecialchars, all special characters get encoded, so instead of seeing some text bold, you will literally see the bold opening and closing tags surrounding the rendered text in the browser.

Upvotes: 1

Related Questions