【问题标题】:using htmlspecialchars in value attribute of text input在文本输入的值属性中使用 htmlspecialchars
【发布时间】:2012-07-12 14:43:01
【问题描述】:

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

我试过了:

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

但它将引号输出为&amp;quot;&amp;#039;,这不是我想要的。我希望文本输入实际上包含用户键入的引号。

我应该使用 php 函数还是 javascript 函数来转义字符串?如果我不转义它,我会收到一个 javascript 错误,因为 $dbValue 字符串中的引号正在与值属性引号交互。

【问题讨论】:

  • 同样的问题。我只使用 htmlspecialchars($value); 解决了 t即使将 é、ô、ñ 与 '' 和 "混合使用,这也是完美的

标签: php attributes escaping quotes htmlspecialchars


【解决方案1】:

不过,这正是您想要的。例如

如果你插入的数据是

Davy "Dead Pirate" Jones

你将它插入到输入字段中,你最终会得到

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

解释如下:

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

相比之下,在做一个 html_entities 之后,你会有

 Davy &quot;Dead Pirate&quot; Jones

并且可以毫无问题地插入到&lt;input&gt; 字段中。

如果输入字段的值包含对用户可见的文字 &amp;quot;,则说明您正在进行一些双重编码。

【讨论】:

    【解决方案2】:

    您需要使用html_entity_decode。这是文档的示例:

    <?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
    ?>
    

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

    【讨论】:

      【解决方案3】:

      您正在寻找 htmlspecialchars 的反面,请尝试使用 html_entity_decode。

      这是您使用 html_entity_decode 的代码。

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

      这是手册的链接 -> http://www.php.net/manual/en/function.html-entity-decode.php

      如果您在使用它时遇到任何问题,您可能想查看这个问题,它有一个常见的编码问题 -> https://stackoverflow.com/a/4638621/1065786

      【讨论】:

        【解决方案4】:

        要将单引号、双引号和 html 标签显示为文本字段值,请尝试使用:

        <?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

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 2016-08-18
          • 2018-03-15
          • 1970-01-01
          • 2013-09-03
          • 1970-01-01
          • 1970-01-01
          • 2015-05-11
          相关资源
          最近更新 更多