在文本输入的value属性中使用htmlspecialchars

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.

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

Your looking for the opposite of htmlspecialchars, try using html_entity_decode.

Here is your code using html_entity_decode.

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

Here is a link to the manual -> http://www.php.net/manual/en/function.html-entity-decode.php

If you have any problems using this you might want to check out this question, which has a common encoding problem -> https://stackoverflow.com/a/4638621/1065786

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.

To display single, double quotes and html tags as text field value try to use:

<?php
$formVal = htmlspecialchars($dbValue, ENT_COMPAT, 'utf-8');
// or this:
// $formVal = htmlspecialchars($dbValue);
?>

<!-- html -->
<form>
<input type="text" name="myTextInput" value="<?php echo $formVal; ?>" />
</form>

http://www.sitepoint.com/form-validation-with-php
https://www.inanimatt.com/php-output-escaping.html