带有自定义链接的PHP动态页面

时间:2012-11-03 14:51:21

标签: php dynamic-pages

以下代码的工作原理如下:

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

我该怎么做?

由于

1 个答案:

答案 0 :(得分:3)

有两个选项,您可以始终在子文件夹中查找文件,或者您可以拥有一个特殊的页面列表,其中包含自己的路径,就像使用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");