<?php
// get all files from pages/ with .php extension
$pages = glob('pages/*.php');
foreach ($pages as $page) {
// remove path
$page_clean = str_replace('pages/', '', $page);
// put it in an array
$allowed_pages = array($page_clean);
// determine that the lank will be index.php?page=%
$page = $_GET['page'] . '.php';
// load page
if(in_array($page, $allowed_pages)) {
include('pages/' . $page);
} else {
echo "Page not found.";
}
}
?>
它确实包含了我呼吁的页面,但它也回应了“找不到页面”。我在这里做错了什么?
一个人爱
答案 0 :(得分:2)
if块不应该在循环中。此外,您正在构建错误的数组。尝试:
<?php
// get all files from pages/ with .php extension
$pages = glob('pages/*.php');
$allowed_pages = array();
foreach ($pages as $page) {
// remove path
$page_clean = str_replace('pages/', '', $page);
// put it in an array
$allowed_pages[] = $page_clean;
}
// determine that the lank will be index.php?page=%
$page = $_GET['page'] . '.php';
// load page
if(in_array($page, $allowed_pages)) {
include('pages/' . $page);
} else {
echo "Page not found.";
}
答案 1 :(得分:2)
您不应该在每个请求上浏览整个目录,只是为了查看给定文件是否存在。只需检查该特定文件是否存在:
if (strpos($page, '..') !== false || strpos($page, '/') !== false) {
// invalid value, but you better use a whitelist than a blacklist like I did
} else {
if (is_file('pages/'.$page.'.php')) {
// file exists
} else {
// file doesn’t exist
}
}
答案 2 :(得分:1)
我会这样做:
if(!isset($_SESSION['allowed_pages'])) {
$_SESSION['allowed_pages'] = array_map('basename', glob('pages/*.php'));
}
$page = $_GET['page'] . '.php';
if(in_array($page, $_SESSION['allowed_pages'])) {
include("pages/$page");
}else {
echo 'Page not found.';
}
每次会话只加载一次页面列表,并清除显式循环以清除glob中的页面名称。