Escape double quotes with variable inside HTML echo [duplicate]
Asked Answered
S

3

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']."
Sweettalk answered 16/12, 2013 at 22:56 Comment(1)
With htmlspecialcharsChartism
T
65

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
Thiazole answered 16/12, 2013 at 22:59 Comment(4)
FYI, the defaults for htmlspecialchars should suffice for a double-quoted value attribute so you can safely leave off the second and third arguments.Memo
@Memo The defaults should suffice, but they historically didn't :)Metaphysical
Biggest problem with PHP is its history :)Memo
the defaults for htmlspecialchars should suffice for a double-quoted value Nope, at least for me I need a ENT_QUOTES for htmlspecialchars to workBahaism
B
4

Use htmlentities:

echo "<input type=\"hidden\" name=\"id\" value=\"".htmlentities($row['id'])."\" />";
Behoove answered 16/12, 2013 at 22:58 Comment(2)
this doesn't seem to answer to the OP. (where the question seems to be how to escape the html attribute value)Quean
Fair point - I misread the question originally. Edited.Behoove
H
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'].'" />';
Hyperpituitarism answered 16/12, 2013 at 22:59 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.