PHP动态包含Index.php的帮助?

时间:2013-09-27 16:24:27

标签: php php-include

我需要有人让我知道这个问题的解决方案。我正在尝试在我的index.php文件上创建一个include,因此当用户单击导航栏上的链接时,index.php上的内容会发生变化。下面的代码效果很好,除非我去index.php,因为它不是数组的一部分,它调用main.php两次,而不是一次。我知道这是因为最后一部分说:

    else {
    include('main.php');
    }

然而,我需要一个解决方案,因为我不擅长PHP。 这是我的完整代码。

    <?php
    // Place the value from ?page=value in the URL to the variable $page.
    $page = $_GET['id'];
    // Create an array of the only pages allowed.
    $pageArray = array('index','css-pub1','page2','page3','page4','page5','page6');
    // If there is no page set, include the default main page.
    if (!$page) {
    include('main.php');
    }
    // Is $page in the array?
    $inArray = in_array($page, $pageArray);
    // If so, include it, if not, emit error.
    if ($inArray == true) {
    include(''. $page .'.php');
    } 
    else {
    include('main.php');
    }
    ?>

4 个答案:

答案 0 :(得分:1)

尝试使用include_once代替include

include_once($page . '.php');
//...
include_once('main.php');

答案 1 :(得分:1)

只需删除

if (!$page) {
    include('main.php');
}

让else处理main.php

答案 2 :(得分:0)

这是因为您试图获取错误的$_GET参数。应该是:

$page = $_GET['page'];

如果您的评论准确无误。

答案 3 :(得分:0)

我已经对问题和修复程序的代码进行了评论。

<?php
// initilize $page
$page='';
// Place the value from ?page=value in the URL to the variable $page.
if (isset($_GET['id'])){ // check if the page is set
    $page = $_GET['id'];
}
// Create an array of the only pages allowed.
$pageArray = array('index','css-pub1','page2','page3','page4','page5','page6');

/* This section is not needed
// If there is no page set, include the default main page.
if (!$page) {
include('main.php');
}
*/

// Is $page in the array?
$inArray = in_array($page, $pageArray);
// If so, include it, if not, emit error.
if ($inArray == true) {
include(''. $page .'.php');
} 
else {
// If there is no page set, include the default main page.
// this also does the same thing as the commented if loop above
include('main.php');
}
?>