有没有什么方法可以安全地包含页面而不将它们全部放入数组中?
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);
}
我应该添加什么才能使其非常安全?
我这样做是因为我不喜欢必须包含必须包含在所有页面上的内容。 “包含页眉 > 内容 > 包含页脚”方式。我也不想使用任何模板引擎/框架。
Thanks.
您当前实施的弱点是……
- 正则表达式只是测试字符串的开头,所以“
images/../../secret
”会过去,并且
- 未经进一步验证,“
index
” 也将是一个有效值并会导致递归。
为了确保您的实施安全,最好将所有要包含的内容放在自己的目录中(例如“includes
” and “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!
}
Note: realpath
如果文件存在,则返回给定相对路径的绝对路径并且false
否则。所以file_exists
没有必要。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)