这是否足以验证php中的产品ID ?


Would this be sufficient validation of a product ID in php?

我在一个非常小的网站上工作,使用codeigniter的项目数量非常有限。

在脚本开始时,产品模型获得整个产品列表,并将结果作为数组存储为该模型的属性。

产品ID只是从数据库中自动增加的主键。当有人将产品添加到购物车时,ID会通过POST发送。然后检查三件事:

  • $id可以是整数吗?
  • 该整数是否超过产品总数?
  • 此整数是否与产品ID匹配?

基本上-尽管稍微简化-我这样做:

// Count total number of items
$total = count($this->productArray)
if (!(int)$id || $id > $total)
    return false;
foreach($this->productArray as $product) {
    if ($product['id'] == $id)
        return true;
}
return false;

您错过了使用数据库的一个主要好处,那就是它非常擅长这类事情。

不应该将所有产品加载到内存中,然后在PHP中执行自己的搜索,而应该使用像select * from products where id = :id这样的SQL查询在数据库中搜索所请求的产品。

Does this integer exceed the total number of products?

这并不总是正确的。一旦他们删除产品,这将不同步。

也就是说,更好的想法是将id转换为整数,并直接在DB上查询产品。不检查预加载的数组;