如何设置 HTML 值属性(带空格) [英] How to set HTML value attribute (with spaces)

查看:41
本文介绍了如何设置 HTML 值属性(带空格)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我使用 PHP 设置 HTML 表单输入元素的值时,只要数据中没有任何空格,它就可以正常工作.

When I use PHP to set the value of a HTML form input element, it works fine provided I don't have any spaces in the data.

<input type="text" name="username"
<?php echo (isset($_POST['username'])) ? "value = ".$_POST["username"] : "value = """; ?> />

如果我输入Jonathan"作为用户名,它会按预期重复给我.但是,如果我输入Big Ted",则在提交表单时只会重复返回Big".

If I enter "Jonathan" as the username, it is repeated back to me as expected. If I enter "Big Ted", however, I only get "Big" repeated back when I submit the form.

注意$_POST["Username"] 变量是正确的;当我使用 PHP 回显它时,它被设置为Big Ted".

Note that the $_POST["Username"] variable is correct; when I echo it using PHP, it is set to "Big Ted".

推荐答案

引用它.否则,空格将成为属性分隔符,空格之后的所有内容都将被视为元素属性.在浏览器中右键单击页面并查看源代码.它不应该是这样的(另见语法高亮颜色):

Quote it. Otherwise the space will just become an attribute separator and everything after spaces will be seen as element attributes. Rightclick page in webbrowser and view source. It should not look like this (also see syntax highlight colors):

<input value=Big Ted>

而是这个

<input value="Big Ted">

更不用说当有人在他的名字中有引号时这仍然会中断(因此您的代码对 XSS 敏感 攻击).使用 htmlspecialchars().

Not to mention that this would still break when someone has a quote in his name (and your code is thus sensitive to XSS attacks). Use htmlspecialchars().

启动示例:

<input value="<?php echo (isset($_POST['username']) ? htmlspecialchars($_POST['username']) : ''); ?>">

这篇关于如何设置 HTML 值属性(带空格)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆