0

下面的代码是这样工作的:

http://www.website.com/?page=home将从中提取内容http://www.website.com/home.php

- 或者 -

http://www.website.com/?page=About将从中提取内容http://www.website.com/About.php

代码:

// Set the default name 
$action = 'home'; 

// Specify some disallowed paths 
$disallowed_paths = array('admin'); 

if (!empty($_GET['page'])) { 
    $tmp_action = basename($_GET['page']); 
    // If it's not a disallowed path, and if the file exists, update $action 
    if (!in_array($tmp_action, $disallowed_paths) && file_exists("{$tmp_action}.php")) 
        $action = $tmp_action; 
} 
// Include $action 
include("$action.php"); 
?>

上面的代码适用于我的所有页面,但现在我有一个自定义链接,我需要添加它http://www.website.com/?page=Search来从中提取内容,http://www.website.com/search/search.php而不是http://www.website.com/Search.php

我怎样才能做到这一点?

谢谢

4

1 回答 1

3

有 2 个选项,您可以随时在子文件夹中查找文件,或者您可以有一个特殊的页面列表,其中包含自己的路径,就像使用 disallowed_pa​​ths 一样。

$special_paths = array(
    "search" => "search/search.php",
);

if(in_array($_GET['page'], $special_paths)) {
    $action = $special_paths[$_GET['page']];

这意味着如果将来存在另一个具有不同路径的特殊页面,您可以简单地将其添加到数组中。

完整的代码将是:

<?php
    // Set the default name
    $action = 'home.php';

    // Specify some disallowed paths
    $disallowed_paths = array('admin');

    // special paths
    $special_paths = array(
            "search" => "search/search.php",
            "special_b" => "a/different/lengthier/path/file.php",
    );

    if (!empty($_GET['page'])) {
            $tmp_action = basename($_GET['page']);

            // If it's not a disallowed path, and if the file exists, update $action
            if (!in_array($tmp_action, $disallowed_paths) && file_exists("{$tmp_action}.php")) {
                    $action = $tmp_action.".php";
            } elseif(isset($special_paths[$tmp_action])) {
                    $action = $special_paths[$tmp_action];
            }
    }

    // Include $action
    include("$action");
于 2012-11-03T14:57:55.780 回答