Search code examples
phpattributesescapingquoteshtmlspecialchars

using htmlspecialchars in value attribute of text input


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.


Solution

  • You'll want to use html_entity_decode. Here's an example for the documentation:

    <?php
    $orig = "I'll \"walk\" the <b>dog</b> now";
    
    $a = htmlentities($orig);
    
    $b = html_entity_decode($a);
    
    echo $a; // I'll &quot;walk&quot; the &lt;b&gt;dog&lt;/b&gt; now
    
    echo $b; // I'll "walk" the <b>dog</b> now
    ?>
    

    Reference: http://www.php.net/manual/en/function.html-entity-decode.php