有没有办法安全地包含页面而不将它们全部放在一个数组中?
if (preg_match('/^[a-z0-9]+/', $_GET['page'])) {
$page = $_GET['page'].".php";
$tpl = $_GET['page'].".html";
if (file_exists($page)) include($page);
if (file_exists($tpl)) include($tpl);
}
我应该添加什么才能使它非常安全?
我这样做是因为我不喜欢必须包含必须包含在所有页面中的内容."包含标题>内容>包含页脚"-way.我也不想使用任何模板引擎/框架.
谢谢.
您当前实施的弱点是......
images/../../secret"会传递,并且index"也将是一个有效的值,并会导致递归.为了使您的实现安全,最好将所有要包含的内容放在其自己的目录中(例如" includes"和" templates").基于此,您只需确保没有办法退出此目录.
if (preg_match('/^[a-z0-9]+$/', $_GET['page'])) {
$page = realpath('includes/'.$_GET['page'].'.php');
$tpl = realpath('templates/'.$_GET['page'].'.html');
if ($page && $tpl) {
include $page;
include $tpl;
} else {
// log error!
}
} else {
// log error!
}
Run Code Online (Sandbox Code Playgroud)
注意:realpath如果文件存在,false则返回给定相对路径的绝对路径.所以file_exists没有必要.