问题
I need someone to let me know a solution to this issue. I am trying to create an include on my index.php file so when a user clicks a link on my navbar the content on the index.php changes. The code below works great, except when I go to index.php, because it is not part of the array, it calls main.php twice, instead of once. I know this is because of the last portion that says:
else {
include('main.php');
}
However, I need a solution to this because I am not good with php. Here is my full code for the include.
<?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');
}
?>
回答1:
Try to use include_once
instead of include
:
include_once($page . '.php');
//...
include_once('main.php');
回答2:
Just remove
if (!$page) {
include('main.php');
}
and let the else handle main.php
回答3:
It's because you're trying to grab the wrong $_GET
parameter. Should be:
$page = $_GET['page'];
If your comments are accurate.
回答4:
I have commented the code on the problems and fixes.
<?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');
}
?>
来源:https://stackoverflow.com/questions/19055684/php-dynamic-include-help-on-index-php