Assume $string = AX èdfdfdèsèdsè'/\"
(actually, $string
is assigned this value from the DB)
So when I print the following,
echo "<option value='". htmlspecialchars($string) ."'>".$string."</option>";
I get the output,
<option \"'="" value="AX èdfdfdèsèdsè">AX èdfdfdèsèdsè'/\"</option>
How can I properly escape this so that I don't create another useless attribute & instead get the same value as in $string
?
Also, what is the reason Php does not escape $string
as a whole?
You should use htmlspecialchars on the second usage of $string in order to prevent breaking the html with a "<". Inside of the option value quotes it is sufficient to replace the single quotes:
echo "<option value='".str_replace("'","'",$string)."'>".htmlspecialchars($string)."</option>";
Output is:
<option value='AX èdfdfdèsèdsè'/\"'>AX èdfdfdèsèdsè'/\"</option>
An alternate answer would be using htmlspecialchars($value,ENT_QUOTES)
So basically that would be
echo "<option value='". htmlspecialchars($value,ENT_QUOTES)."'>".($value)."</option>";
It seems that neither htmlspecialchars($value)
nor htmlentities($value)
convert single-quotes '
by default unless explicitly setting the ENT_QUOTES
flag.
echo '<option value="', htmlspecialchars($string), '">', htmlspecialchars($string), '</option>';
PHP doesn't escape anything unless you tell it to. ;)