我需要有人让我知道这个问题的解决方案。我正在尝试在我的索引.php文件上创建一个包含,因此当用户单击导航栏上的链接时.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');
}
?>
尝试使用 include_once
而不是 include
:
include_once($page . '.php');
//...
include_once('main.php');
只需删除
if (!$page) {
include('main.php');
}
并让其他处理主.php
这是因为您试图获取错误的$_GET
参数。应该是:
$page = $_GET['page'];
如果您的评论准确无误。
我已经
对代码的问题和修复进行了注释。
<?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');
}
?>