已接收的HTML表单值中的转义引号

时间:2014-02-07 19:13:02

标签: php html input encoding escaping

请查看下面的SSCCE。它是一个简单的HTML表单,带有文本字段和文本区域,两者都包含带引号和标记的字符串。

提交表单后,接收的值将被编码(使用htmlentities),解码(使用html_entity_decode),然后与原始值进行比较(请参阅evaluate的调用SSCCE中的方法)。在我的本地服务器上,这些值是相等的。但是在远程服务器上它们不是,而是所有引号都被转义,即收到\'\"

这是为什么?它是PHP版本的问题吗? (当地:5.4.9,远程:5.3.18)

此外,远程服务器无法处理变音符号(如ä,ö,ü),尽管我在HTML头中指定了UTF-8。为什么?

这是SSCCE:

<?php // sscce.php

function encode($string)
{
    return htmlentities($string, ENT_QUOTES);
}

function decode($string)
{
    return html_entity_decode($string, ENT_QUOTES);
}

function evaluate($string1, $string2)
{
    echo (strcmp($string1, $string2) == 0) ? 'OK' : 'FAIL: ' . $string2;
}

$value = <<<'EOT'
<p>'a' & "b"</p>
EOT;

$encodedValue = encode($value);

$encodedReceivedValueTF = encode(isset($_GET['submit']) ? $_GET['tf'] : '');
$encodedReceivedValueTA = encode(isset($_GET['submit']) ? $_GET['ta'] : '');

$decodedReceivedValueTF = decode($encodedReceivedValueTF);
$decodedReceivedValueTA = decode($encodedReceivedValueTA);

echo '<?xml version="1.0" encoding="UTF-8" ?>', PHP_EOL;
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
        <title>SSCCE</title>
    </head>
    <body>
        <h2>PHP: <?php echo phpversion(); ?></h2>
        <h2>Test Values</h2>
        <form action="sscce.php" method="get">
            <div><input id="tf" name="tf" type="text" size="50" value="<?php echo $encodedValue; ?>" /></div>
            <div><textarea id="ta" name="ta" rows="1" cols="50"><?php echo $encodedValue; ?></textarea></div>
            <div><input id="submit" name="submit" type="submit" value="Perform Test!" /></div>
            <div><a href="sscce.php">Reset</a></div>
        </form>

        <h2>Encoded Values</h2>
        <div>Text Field: <?php echo evaluate($encodedValue, $encodedReceivedValueTF); ?></div>
        <div>Text Area: <?php echo evaluate($encodedValue, $encodedReceivedValueTA); ?></div>

        <h2>Decoded Received Values</h2>
        <div>Text Field: <?php echo evaluate($value, $decodedReceivedValueTF); ?></div>
        <div>Text Area: <?php echo evaluate($value, $decodedReceivedValueTA); ?></div>
    </body>
</html>

1 个答案:

答案 0 :(得分:0)