using htmlspecialchars in value attribute of text input

Devin Crossman picture Devin Crossman · Jul 12, 2012 · Viewed 7.5k times · Source

My question is similar to this question but I'm not using code igniter. I'm echoing variables obtained from a database into the value attribute of a text input. The variables may contain ' or " or any other special chars.

I tried:

<input type="text" name="myTextInput" value="<?= htmlspecialchars($dbValue, ENT_QUOTES); ?>" />

but it outputs quotes as &quot; or &#039; which is not what I want. I want the text input to actually contain the quotes as typed by the user.

should I be using a php function or a javascript function to escape the string? if I don't escape it I get a javascript error because the quotes inside the $dbValue string are interacting with the value attribute quotes.

Answer

Marc B picture Marc B · Jul 12, 2012

That's exactly what you DO want, however. e.g.

if your inserted data is

Davy "Dead Pirate" Jones

and you insert that into an input field literally, you'd end up with

<input type="text" name="..." value="Davy "Dead Pirate" Jones" />

which will be interepreted as follows:

<input> field with attributes:
    text -> 'text'
    name -> '...'
    value -> ' '   (a single space)
    Dead -> 
    Pirate ->
    " ?   danging quote
    Jones ->
    " ? -> another dangling quote

By comparion, after doing an html_entities, you'd have

 Davy &quot;Dead Pirate&quot; Jones

and that can be inserted into the <input> field without issue.

If the input field's value contains a literal &quot; that's visible to the user, then you've got some double-encoding going on.