0

我的 php 代码安全吗?

<?php

$item = (int)$_GET['item'];

if (!isset($_GET['item'])) {
    header('Location: index.php');
    exit;
}

$fileName = "items/" . $item . ".php";

if (file_exists($fileName)) {
    require_once ("items/" . $item . ".php");
} else {
    header('Location: index.php');
}

?>
4

3 回答 3

2

为了更好的安全性,我认为在项目上添加验证应该会更好:

$valid_items = array('item1', 'item2', 'item3');

if(in_array($item, $valid_items)) {
  // something if item is valid item
}
于 2010-11-12T08:04:06.150 回答
1

我可以使用is_int()而不是强制转换。但你的代码对我来说似乎很好。

您应该使用 ExceptionHandler 处理异常消息。

在尝试访问 $_GET['item']之前检查是否定义了 $_GET。

于 2010-11-12T08:07:51.077 回答
0

您可以先检查请求方法的类型,例如

if($_SERVER['REQUEST_METHOD'] != 'GET') { 
       header('Location: index.php'); exit; 
}


if (!isset($_GET['item'])) {
    header('Location: index.php');
    exit;
 }

 $item = (int)$_GET['item']; 
/*
 * just make sure that all you pass is numeric before typecasting it. If you're not                                           
 * sure...you can do this 
 * $item = is_numeric($_GET['item']) ? (int)$_GET['item'] : null; //or 0
 *
 */

 //your code here
于 2010-11-12T09:23:29.043 回答