php htmlspecialchars() 从一种形式到另一种形式
为什么 htmlspecialchars() 不能在每次表单提交后继续对字符进行编码? 看一下下面的示例:
<?php $_POST['txt'] = htmlspecialchars($_POST['txt']); ?>
<form method="post">
<input name="txt" value="<?=$_POST['txt'] ?>" />
<input type="submit" name="save" value="test" />
</form>
您可以在 http://verticalcms.com/htmlspecialchars.php 运行时看到它。
现在执行以下操作
1) Type & into the text field
2) Hit the test button once
3) When the page completes post back, hit the test button again
4) When the page completes post back, view the page source code
在输入框中,值为 & 放大器;
我期待着& 放大器; 放大器;
为什么不是& 放大器; 放大器; ???
Why can't htmlspecialchars() continually encode characters after each form submission? Take a look at the following example:
<?php $_POST['txt'] = htmlspecialchars($_POST['txt']); ?>
<form method="post">
<input name="txt" value="<?=$_POST['txt'] ?>" />
<input type="submit" name="save" value="test" />
</form>
You can see it at running at http://verticalcms.com/htmlspecialchars.php.
Now do the following
1) Type & into the text field
2) Hit the test button once
3) When the page completes post back, hit the test button again
4) When the page completes post back, view the page source code
In the input box, the value is & amp;
I was expecting & amp; amp;
Why is it not & amp; amp; ???
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
这就是 HTML 实体编码。 使用“&”时 在 HTML 属性中,应该对其进行编码。 这就是你正在做的事情。
因此,浏览器读取
并将其转换为“值为 '&' 的文本框小部件”。
对于其他特殊字符也是如此:
将产生一个 " 字符。
当您提交表单时,浏览器会发送这些未编码的值,因此您的 PHP 脚本会像“&”而不是“&”那样接收它。
This simply is HTML entity encoding. When using "&" in an HTML attribute, it should be encoded. And this is what you are doing.
So, the browser reads
and translates it to an "textbox widget with value '&'".
The same would be true for other special chars:
would result in a " character.
When you submit the form, the browser sends these values unencoded, therefore your PHP script receives it like "&", not "&".
为了方便起见,$_POST 中的值已经进行了 html 解码。 因此,当您的脚本启动时,以下情况成立:
[编辑]
看起来这需要进一步解释
当浏览器将像上面这样的表单提交到服务器并使用单个 & 符号作为“txt”的值时,它将以下内容放入请求正文中:
该值被编码,因为浏览器会使用 & 字符连接多个字段,就像
PHP 一样,为了方便程序员,它会获取传输的值并对其进行解码 - 它会从 & 中生成一个 & 符号。 现在我想这就是这个问题的首要原因——我猜我错了。 费迪南德正确回答了实际问题。
The values in $_POST are already html-decoded for convenience. So when your script starts, the following is true:
[edit]
Looks like this needs further explanation
When a form like the one above is submitted to the server by the browser with a single ampersand as the value of 'txt', it puts the following into the body of the request:
The value is encoded because the browser would concatenate multiple fields with an ampersand character like
PHP takes the transmitted values and decodes them for the convenience of the programmer - it makes an ampersand out of & Now I though this was the reason for the question in the first place - guess I got it wrong. The actual question was answered correctly by Ferdinand.