开发者

Is my php codes safe?

开发者 https://www.devze.com 2023-01-24 12:33 出处:网络
Is my php codes safe ? <?php $item = (int)$_GET[\'item\']; if (!isset($_GET[\'item\'])) { header(\'Location: index.php\');

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
0

精彩评论

暂无评论...
验证码 换一张
取 消