32

For a variable inside a echo that contains HTML, where would I add slashes to escape the double quotes?

Example:

echo "<input type=\"hidden\" name=\"id\" value=".$row['id']." />";

This part:

value=".$row['id']."
swiftsly
  • 811
  • 4
  • 16
  • 29

3 Answers3

64

Some tips on outputting HTML with PHP:

  1. Use single quotes so that you don't have to escape the double quotes (when using echo),
  2. Use htmlspecialchars() to properly escape any "rogue" values you may have.

Example using echo:

echo '<input type="hidden" name="id" value="', htmlspecialchars($row['id'], ENT_QUOTES, 'UTF-8'), '" />';

Or printf():

printf('<input type="hidden" name="id" value="%s" />', 
    htmlspecialchars($row['id'], ENT_QUOTES, 'UTF-8')
);

Or, in HTML mode:

?>
<input type="hidden" name="id" value="<?php echo htmlspecialchars($row['id'], ENT_QUOTES, 'UTF-8'); ?>" />
<?php
John Kary
  • 6,703
  • 1
  • 24
  • 24
Ja͢ck
  • 170,779
  • 38
  • 263
  • 309
  • 2
    FYI, the defaults for `htmlspecialchars` should suffice for a double-quoted `value` attribute so you can safely leave off the second and third arguments. – Phil Dec 16 '13 at 23:05
  • 1
    @Phil The defaults *should* suffice, but they historically didn't :) – Ja͢ck Dec 16 '13 at 23:05
  • Biggest problem with PHP is its *history* :) – Phil Dec 16 '13 at 23:06
  • `the defaults for htmlspecialchars should suffice for a double-quoted value` Nope, at least for me I need a `ENT_QUOTES` for `htmlspecialchars` to work – Ng Sek Long Aug 20 '19 at 02:10
4

Use htmlentities:

echo "<input type=\"hidden\" name=\"id\" value=\"".htmlentities($row['id'])."\" />";
elixenide
  • 44,308
  • 16
  • 74
  • 100
0

How about use single quotes so you don't have to escape any quotes. Like so:

echo '<input type="hidden" name="id" value="'.$row['id'].'" />';
Bryan Elliott
  • 4,055
  • 2
  • 21
  • 22