转义 PHP GET 和 POST 值
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/9446063/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Escaping PHP GET and POST values
提问by jribeiro
Possible Duplicate:
The ultimate clean/secure function
可能的重复:
终极清洁/安全功能
I was informed in another thread that this bit of code was pretty useless:
我在另一个线程中被告知,这段代码非常无用:
function getPost($s) {
if (array_key_exists($s, $_POST))
return mysql_real_escape_string(htmlspecialchars($_POST[$s]));
else return false;
}
function getGet($s) {
if (array_key_exists($s, $_GET))
return mysql_real_escape_string(htmlspecialchars($_GET[$s]));
else return false;
}
Can anybody help understand why and how I can make it better please? Links or references are welcome also.
任何人都可以帮助理解为什么以及如何让它变得更好吗?也欢迎链接或参考。
Just trying to always improve :)
只是想总是改进:)
回答by Ry-
Well, it's bad for the same way magic_quotes_gpc is bad. It's magic and will escape everything, whether you want it to or not. Instead, handle the escaping where it's used, and you can change things without any problem. So:
好吧,这与 magic_quotes_gpc 不好的方式一样不好。这很神奇,无论你愿意与否,它都能逃脱一切。相反,在使用它的地方处理转义,您可以毫无问题地更改内容。所以:
function post($key) {
if(array_key_exists($key, $_POST)) {
return $_POST[$key];
}
return false;
}
And do your escaping where it's needed. Otherwise, things can look strange, and unescaping them will defeat the point. Consider this; I input my last name, O'Hara
, in a textbox. You want to echo
it back, but you fetch it using getPost
. Here's what I get back:
并在需要的地方进行逃生。否则,事情可能看起来很奇怪,而逃避它们会失败。考虑一下;我O'Hara
在文本框中输入我的姓氏。你想要echo
它回来,但你使用getPost
. 这是我的回复:
O\'Hara
奥哈拉
Did you htmlspecialchars
it again? Well, then I get:
你htmlspecialchars
又做了吗?好吧,然后我得到:
O\'ara
奥拉
or something. This happens to me a lot and it's incredibly annoying - please don't do it.
或者其他的东西。这种情况经常发生在我身上,而且非常烦人 - 请不要这样做。
回答by spencercw
I wouldn't say useless, just a bit misguided. You should do the escaping immediately before you use it in the context it needs to be escaped for. For example, if you want to send the value back to the browser you might do this:
我不会说没用,只是有点误导。您应该在需要转义的上下文中使用它之前立即进行转义。例如,如果您想将值发送回浏览器,您可以这样做:
echo htmlspecialchars($_GET['name']);
But if you want to send it to the database you might do this:
但是如果你想把它发送到数据库,你可以这样做:
mysql_query(... 'INSERT INTO users VALUES ("'.mysql_real_escape_string($_GET['name']).'")');
With your method you are fixed in what you can do with it. If you do this:
用你的方法,你可以用它做什么。如果你这样做:
echo getGet('name');
You are going to print out a MySQL escaped string rather than the actual name.
您将打印出 MySQL 转义字符串而不是实际名称。