动态包含方法

时间:2010-07-04 16:25:41

标签: php

以下包括最佳实践方法和原因?

$page = $_GET['page'];

方法1

$pages = array('home', 'blog', 'about');
if( in_array($page, $pages) )
{
    include($page.'.php');
{
else
{
   die('Nice Try.');
}

方法2

if($page = 'home'){
include('home.php');
}else if($page = 'blog'){
include('blog.php');
}else if($page = 'about'){
include('about.php');
}

方法3

if(str_replace("http://", "gth://", $page) == $page){
include_once $page;
}else{
       die('Nice Try.');
}

或任何其他解决方案?我不喜欢方法1和2,因为每次添加新页面时总是需要更新。

2 个答案:

答案 0 :(得分:3)

扩展/维护第一种方式最简单,第二种方式更糟。第三种方式是没办法,因为它依赖于用户输入来要求页面...它将是一个安全漏洞

答案 1 :(得分:2)

我相信第一个是最好的。你可以尝试第二个,但这是为新手。第三个是 BIG NO ,因为任何新鲜的黑客都可以破解你的“if”条件,&更多的漏洞将开始蔓延。

至于你的问题,在向数组添加新页面时,每次创建新页面时,对于第一种方法,我都有一个解决方案: -
假设您将所有新页面放在一个文件夹“abc”中。现在只需编写一个文件代码,以读取该文件夹中存在的所有文件/页面: -

<?php
$page = $_GET['page'];
$pages = array();
/**
 * If you are using all the pages existing in the current folder you are in,
 * then use the below variable as:-
 * $path = ".";
 */
$path = 'abc/'; // Change the Path here, related to this Folder name
$handle = opendir($path);
while (($file = readdir($handle)) !== false) {
    $pages[] = $file;
}
closedir($handle);

if( in_array($page, $pages) ) {
    include($page.'.php');
}
else {
    die('Nice Try.');
}
?>

所以你看到数组被动态填满,而不需要提到你每次创建的所有页面。而您只使用第一种方法。并将包含页面保存在一个单独的文件夹中,您需要每次都将其包含在其他主页中。

希望它有所帮助。

相关问题