-2

I have two pieces of code. Can you please tell me which one is correct and more secure?

<input type="text" class="form-control contact__form-control"    placeholder="Your Name *" id="name" value="<?php echo htmlspecialchars ($name); ?>">
<?php echo "<span class='text-danger'>$nameError</span>";?>

or

<input type="text" class="form-control contact__form-control" placeholder="Your Name *" id="name" value="<?php echo htmlspecialchars ($name); ?>">
<?php echo htmlspecialchars ("<span class='text- danger'>$nameError</span>");?>

I have seen everyone to use the 1st one but i read that in PHP when you echo something its good to add htmlspecialchars for security reason. So i am wondering if the second piece of code is correct. Will the bootstrap alert class will work after the htmlspecialchars

G Tsirigos
  • 83
  • 9

1 Answers1

1

When you need to output plain text on an HTML page, you should HTML-escape it, otherwise HTML tags will be interpreted, well, as HTML.

Even if some text is not supposed to contain HTML tags, i.e. a user name, if it comes as input from the user, it can be forged to contain dangerous HTML tags, so for safety reasons you can HTML-escape it anyway.

But escape only the text, don't escape the tags that surround it.

<span class='text-danger'><?php echo htmlspecialchars($nameError); ?></span>

Alternatively, you can sanitize user input at the beginning of the script; e.g. remove all non-alphanumeric characters from a user name. Then you won't have to HTML-escape it anymore.

rustyx
  • 80,671
  • 25
  • 200
  • 267