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

Dev*_*man 2 php quotes attributes escaping htmlspecialchars

我的问题类似于这个问题,但我没有使用代码点火器.我将从数据库获取的变量回显到文本输入的value属性.变量可能包含"或"或任何其他特殊字符.

我试过了:

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

但它输出的引号为&quot;&#039;不是我想要的.我希望文本输入实际包含用户输入的引号.

我应该使用PHP函数或JavaScript函数来逃避字符串?如果我不逃避它我得到一个javascript错误,因为$ dbValue字符串中的引号与值属性引号交互.

Mar*_*c B 5

然而,这正是你想要的.例如

如果你插入的数据是

Davy "Dead Pirate" Jones
Run Code Online (Sandbox Code Playgroud)

然后你按字面意思将它插入输入字段,你最终会得到

<input type="text" name="..." value="Davy "Dead Pirate" Jones" />
Run Code Online (Sandbox Code Playgroud)

这将被解释如下:

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

通过比较,在做了一个html_entities后,你就可以了

 Davy &quot;Dead Pirate&quot; Jones
Run Code Online (Sandbox Code Playgroud)

并且可以<input>毫无问题地插入到现场.

如果输入字段的值包含&quot;用户可见的文字,那么您将进行一些双重编码.