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

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

问题描述

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

 < input type =textname =username
<?php echo(isset($ _ POST ['username']))? value =。$ _ POST [username]:value = \\; ?> />

如果我输入Jonathan作为用户名,它会按预期重复回到我身上。然而,如果我输入Big Ted,那么当我提交表单时,我只会重复Big。注意 $ _ POST [用户名] 变量是正确的;当我使用PHP回显它时,它被设置为Big Ted。

解决方案

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

 < input value = Big Ted> 

而是这个

 <输入值=Big Ted> 

更不用说,当某人的名字中有一个引号时,因此对 XSS 敏感攻击的)。使用 htmlspecialchars()



开球示例:

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


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 = \"\""; ?> />

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.

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>

but rather this

<input value="Big Ted">

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().

Kickoff example:

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

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

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