我有一个链接缩略图列表。每个缩略图都有一个带有一个变量的链接。
<a href="index.php?id=1"><img src="thumb1.jpg">
<a href="index.php?id=2"><img src="thumb2.jpg">
等...
现在,我已更新网站以使用网址重写。想法是我有像这样的链接
<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);
可以做到,主要的是,我如何防止传递id构成安全威胁?
干杯, 阿莱克斯
答案 0 :(得分:2)
url-rewriting部分本身并没有真正引入任何新的安全威胁,问题是使用mysql_*
函数(不推荐使用)而不是转义$id
请求变量。
如果您害怕SQL注入(应该是这样),要么在查询中使用它之前转义$ id变量,要么使用预处理语句(然后切换到mysqli或PDO,你应该在任何导致mysql_ *被弃用的原因!)。
始终验证并转义您将要在数据库查询中使用的任何内容。
答案 1 :(得分:0)
请注意SQL injection vulnerabilities并确保您清理任何用户输入或考虑使用prepared statements。
答案 2 :(得分:0)
对于特定的实现,我留下这个封装的代码片段
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
}
在这个例子中,已经准备好使用简单的incomming参数,但我仍然使用预准备语句来保持一致性(我自己的代码约定)
警告:这使用某种形式的半成品MVC / MVP / MVVM(我不再确定)类型架构
如果您使用网址重写来进一步实施您的SEO链接,您实际上可以制作这样的href网址
protocol://host/controller/action/getParam1/getParam2
// usage
http://yourhost/browsethumbs/aNumber