我有一个链接缩略图的列表。每个缩略图都有一个带有一个变量的链接。
<a href="index.php?id=1"><img src="thumb1.jpg">
<a href="index.php?id=2"><img src="thumb2.jpg">
等等。。。
现在,我已经更新了网站,使用url重写。想法是我有这样的链接
<a href="gallery/?id=1"><img src="thumb1.jpg">
<a href="gallery/?id=2"><img src="thumb2.jpg">
或者类似的东西。
在登录页上,我使用$id
执行MySQL
查询,并显示带有该id的图库中的所有图片。
$pictures = mysql_query("SELECT * FROM t_gallery where id=$id",$db);
这能做到吗?最重要的是,我如何防止通过身份证构成安全威胁?
干杯,Aleks
url重写部分本身并没有真正引入任何新的安全威胁,问题是使用了mysql_*
函数(已弃用),并且没有转义$id
请求变量。
如果您害怕SQL注入(应该是这样),请在查询中使用$id变量之前对其进行转义,或者使用准备好的语句(然后切换到mysqli或PDO,在任何情况下都应该这样做,这会导致mysql_*被弃用!)。
始终验证和转义将要在数据库查询中使用的任何内容。
请注意SQL注入漏洞,并确保清除任何用户输入或考虑使用准备好的语句。
对于特定的实现,我将这段封装的代码留给
function ControllerAction($id=null) {
// I like to formalize on entry; this is supposed to be an absolute integer and nothing else
$id = abs((int)$id);
$q = 'SELECT * FROM t_gallery where id = ?'; // placeholder
// use PDO, it's safe and very comfortable
$pdo = get_pdo_connection($whatever_you_need);
// prepare it because it has placeholders, and because there is external input comming in
$stmt = $pdo->prepare($q);
// execute it
$stmt->execute(array($id)); // read the reference documentation to understand this clearly
// now the stmt object holds the results
return $stmt->fetchObject();// whatever you like here, I like to make a DAO
}
在这个例子中,简单的输入参数已经准备好使用了,但我仍然使用准备好的语句来保持一致性(我自己的代码约定)
警报:这使用了某种形式的半途而废的MVC/MVP/MVM(我不确定了)类型的架构
如果您使用Url重写来进一步实现SEO链接,您实际上可以将href Url设置为这样
protocol://host/controller/action/getParam1/getParam2 // usage http://yourhost/browsethumbs/aNumber