Is my php codes safe ?
<?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.p开发者_开发问答hp');
}
?>
For better security, I think it should be better if you add validation on item:
$valid_items = array('item1', 'item2', 'item3');
if(in_array($item, $valid_items)) {
// something if item is valid item
}
I may use is_int() instead of casting. But your code seems fine to me.
You should handle exception messages with a ExceptionHandler.
Check if $_GET is defined before trying to access $_GET['item'].
You can check first for the type of request method, something like
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
精彩评论