我正在使用:
<?php
$file = $_GET['page']; //ie: http://localhost/?page=index
include "php/{$file}.php";
?>
,但我需要知道什么是调用$file
变量的最安全方法,以调用include
。
我在想:
//-replace '.' with ''
//-replace '/' with ''
//-replace '' with ''
但是我确定有一种更好的方法,所以我要寻求您的帮助。我需要它非常安全。
谢谢。
如果您需要非常安全,即使在修剪后也不要随身携带。而是在获得的变量与需要包含的文件之间使用类似于二进制的关联:
<?php
$file = $_GET['page'];
$allowed_pages = array('index', 'profile', 'legal', 'about');
if (in_array($file, $allowed_pages)) {
include "php/" . $file . ".php");
} else {
die("The page " . $file ." does not exist");
}
?>
这样,您将从不 我想无论您做什么,您都无法信任用户数据。 如果您有限数量的可用文件,则应制作它们的数组并允许它们。 编辑: 另一种方法是扫描您的目录并删除您不需要的文件和DIR。$allowedFiles = array('index','somewhere','elswhere');
if (!in_array($file,$allowedFile))
exit ('File Not found');
else
include("php/{$file}.php");
$filesInDir = scandir("./php");
$allowedFiles = array_diff(array(".","..","protected.php"),$filesInDir);
if (!in_array($file.".php",$allowedFile))
exit ('File Not found');
else
include("php/{$file}.php");