如何保护我的代码


How to Secure My Code

我正在为一家公司编写一个简单的基于web的网站,以便在其网站上展示产品。它需要相当容易维护。我无法使用数据库。我使用多维数组来存储产品信息,并使用产品密钥进行检索。

我主要关心的是安全问题。我能花在这方面的时间非常有限——所以,我没有带宽来构建任何更严肃的东西。如果你看到任何看起来明显不好的东西,请告诉我如何修补。

以下是带有产品密钥的示例URL:http://example.com/products.php?productKey=widget

以下是获取产品密钥、验证其有效性并检索产品信息的代码:

// obtain merchandise variables
include 'merch.vars.php';
// assign a default value
$productKey = 'placeholder';
// check to see if a value was passed
if (isset($_GET["productKey"])) {
    // create array of product keys
    $productArrayKeys = array_keys($product);
    // check if value passed to page exists in product key array
    if (in_array($_GET["productKey"], $productArrayKeys)) {
        // value exists - assign to $productKey
        $productKey = $_GET["productKey"];
    }
}

以下是产品多维数组的示例:

$product = array(
    "placeholder" => array(
        item_title => "Placeholder Title",
        item_image_url => "placeholder.png",
        item_price => "0.00",
        item_description => "Placeholder Description",
        item_quantity => 1,
        product_icons => false
    ),
    "widget" => array(
        item_title => "Product Title",
        item_image_url => "widget.png",
        item_price => "15.00",
        item_description => "Product Description",
        item_quantity => 1,
        item_category => array(
            small => "Small",
            medium => "Medium",
            large => "Large",
            Xlarge => "XLarge"
        ),
        product_icons => true
    )
);

看起来你已经有了一个不错的方法来验证某人不能传入你的产品数组中不存在的东西。也就是说,您对它从products数组中检索信息的描述/评论并不完全有效。检查后,你需要像一样的东西

$chosenProduct = $product[$productKey];

以便实际获得产品信息。

还有一个订单点,在你的$product数组中,它真的应该有你所有的密钥这样报价:

$product = array(
    "placeholder" => array(
        "item_title" => "Placeholder Title",
        "item_image_url" => "placeholder.png",
        "item_price" => "0.00",
        "item_description" => "Placeholder Description",
        "item_quantity" => 1,
        "product_icons" => false
    ),
    "widget" => array(
        "item_title" => "Product Title",
        "item_image_url" => "widget.png",
        "item_price" => "15.00",
        "item_description" => "Product Description",
        "item_quantity" => 1,
        "item_category" => array(
            "small" => "Small",
            "medium" => "Medium",
            "large" => "Large",
            "Xlarge" => "XLarge"
        ),
        "product_icons" => true
    )
);

在不引用的情况下,PHP会假设您使用的是常量。它会尝试查找常量的值,并假设您没有任何与这些名称匹配的常量,它会发出通知,告诉您这是假设您打算使用字符串。引用将使其性能更好,并且不会与使用这些键定义的任何常量发生冲突。

我想你想要这样的东西:

if (isset($_GET["productKey"]) && isset($product[$_GET['productKey']])) {
    $productKey = $_GET["productKey"];
    print_r($product[$productKey]);
}else{
    echo 'product does not exits / productKey not set';
}