PHP包含帮助

时间:2011-08-02 13:43:30

标签: php include

我需要一些PHP包含编码方面的帮助。以下是我将要谈论的代码:

<?php 
$default = 'about'; //Whatever default page you want to display if the file doesn't exist or you've just arrived to the home page. 
$page = isset($_GET['p']) ? $_GET['p'] : $default; //Checks if ?p is set, and puts the page in and if not, it goes to the default page. 
$page = basename($page); //Gets the page name only, and no directories. 
if (!file_exists('content/'.$page.'.php'))    { //Checks if the file doesn't exist 
    $page = $default; //If it doesn't, it'll revert back to the default page 
    //NOTE: Alternatively, you can make up a 404 page, and replace $default with whatever the page name is. Make sure it's still in the inc/ directory. 
} 
include('content/'.$page.'.php'); //And now it's on your page! 
?> 

好的,这会将“about.php”称为我的索引页面,因为它后面有编码。但是,我希望默认索引页面能够调用url页面,例如“http://www.mywebsite.com/frontpage/”。我尝试用url替换'about',它只是在url的末尾添加'.php'扩展名,在url的开头添加'/ content'。因此,我收到PHP错误。

有人可以帮助我使用我想要实际做的代码(如上所述)吗?谢谢:))

3 个答案:

答案 0 :(得分:0)

您可以使用include的file_get_contents instat。 只需检查它是否是外部URL。 想想安全。也许你可以在不检查$ _GET ['p']的情况下访问某些配置文件。

答案 1 :(得分:0)

单独使用PHP无法做到这一点,因为Web服务器需要知道如何处理该URL。如果您正在使用Apache,则可以使用mod_rewrite将example.com/facepage作为首页PHP脚本实际所在的位置。

另一种选择是在文档根目录中创建一个frontpage目录并将index.php添加到该目录,然后使index.php加载实际的首页(或者让index.php保存首页内容) )。

编辑:我可能误解了这个问题:如果你想让那个脚本从另一个目录加载默认页面,你可以这样做:

if( $page == $default ) {
    include( 'path/to/frontpage/file.php' );
}
else {
    include('content/'.$page.'.php');
}

答案 2 :(得分:0)

如果我理解你的问题,应该这样做:

<?php 
$default = 'about'; //Whatever default page you want to display if the file doesn't exist or you've just arrived to the home page. 
$page = isset($_GET['p']) ? $_GET['p'] : $default; //Checks if ?p is set, and puts the page in and if not, it goes to the default page. 
$page = basename($page); //Gets the page name only, and no directories. 
if (!file_exists('content/'.$page.'.php'))    { //Checks if the file doesn't exist 
    $page = $default; //If it doesn't, it'll revert back to the default page 
    //NOTE: Alternatively, you can make up a 404 page, and replace $default with whatever the page name is. Make sure it's still in the inc/ directory. 
}
else {
    $page = 'content/'.$page.'.php';
}
include($page); //And now it's on your page! 
?>
但是,我应该提到这是一个坏主意。您应该将其限制为白名单,而不是仅包含文件(如果存在)。与if (in_array($page,array('frontpage,'about',...)) ...一样。

相关问题