如何在 php 中清理从 url 到 mysql 的简单 _GET 输入
我有一个简单的 php 脚本,希望人们可以简单地访问 http://mydomain.com/get.php?id=TEXTMASH-1FD0066D-F75A-5D0C-6784-2FA0D055B0D7 之类的内容并启动这个文本块来自我的 mysql 数据库。我对 php 很陌生。知道所有预期的 ID 都应采用 TEXTMASH-1FD0066D-F75A-5D0C-6784-2FA0D055B0D7
格式,如何“清理” _GET 以使其不易受到任何攻击?我看过一些指南,但我只是不明白。有人介意给我看看吗?我真的很感激。
<?php
include_once("../../extern/dbinclude.php");
$id= $_GET['id'];
$result = mysql_query("SELECT text FROM mytable WHERE id='$id'")
or die(mysql_error());
$row = mysql_fetch_array($result);
if($row)
{
echo nl2br($row['text']);
} else {
?>
<h2>Invalid URL</h2>
<?php
}
I have a simple php script where hopefully people can simply go to something like http://mydomain.com/get.php?id=TEXTMASH-1FD0066D-F75A-5D0C-6784-2FA0D055B0D7
and pull up this text block from my mysql db. I'm very new to php. Knowing that all of expected IDs should be something in the format of TEXTMASH-1FD0066D-F75A-5D0C-6784-2FA0D055B0D7
how can I "sanitize" the _GET so it's not vulnerable to any attacks? I've looked at some guides but, i'm just not getting it. Anyone mind showing me? I'd really appreciate it.
<?php
include_once("../../extern/dbinclude.php");
$id= $_GET['id'];
$result = mysql_query("SELECT text FROM mytable WHERE id='$id'")
or die(mysql_error());
$row = mysql_fetch_array($result);
if($row)
{
echo nl2br($row['text']);
} else {
?>
<h2>Invalid URL</h2>
<?php
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您可以使用 mysql_real_escape_string 或可能的正则表达式来检查输入。适合您情况的一种可能的正则表达式:
You could either use
mysql_real_escape_string
or possibly a regex to check the input. One possible regex for your case:到目前为止,最好的方法是通过准备好的声明。到目前为止,其他答案建议使用 mysql_real_escape_string ,它可以工作,但很容易被开发人员和 PITA 错过,不得不一直使用。由于很容易错过并且很难找到这些错误,因此它不是一个可靠或可维护的解决方案。
准备好的语句可以消除过程中的这种痛苦,并自动适当地转义事情。
您可以在SO其他地方找到我们的更多信息。
By far the best way to do this is through prepared statements. The other answers so far have suggested using
mysql_real_escape_string
, which works, but is easily missed by a developer and a PITA to have to use all the time. Because it's so easy to miss and so hard to locate those errors, it's not a reliable or maintainable solution.Prepared statements take this pain out of the process and automatically escape things appropriately.
You can find our more info elsewhere on SO.
清理输入的两个主要方面:
每当您显示字符串变量时,请确保转义任何 HTML 字符。
Two main aspects to sanitizing the input:
And whenever you display a string variable, make sure to escape any HTML characters.