Reputation: 206078
I'm trying to write a list of files and drop them into an array. Have to change the content on a page calling external contents.
I've found this little piece of code and trying to make it work. LINK (last comment)
$all_pages=array("main","page_two","page_three");
$page = $_GET['page'];
if( isset($page) and array_key_exists("$page", $all_pages) ) // added a missing ')'
{
include('subfolder/folder/'.$_GET['$page'].'.html');
}
well, this does not work. Just can't get to the right file. (the content shows always empty).
I (try to) call the files like:
<ul>
<li><a href="template.php?main">Main content</a></li>
<li><a href="template.php?page_two">Second content</a></li>
<li><a href="template.php?page_three">Third content</a></li>
</ul>
Thanks in advance!
Upvotes: 3
Views: 75
Reputation: 59699
Change array_key_exists
to in_array
. Also, the variable $page could be set but be empty, check to make sure it's not empty with if( !empty( $page) && ...
etc.
Upvotes: 1
Reputation: 145482
You would have to use in_array()
to test for allowed values. array_key_exists
would require the page names to be array keys.
Secondly, $_GET["page"]
will be empty, as you didn't have a get parameter of that name. You must adapt your links:
<li><a href="template.php?page=main">Main content</a></li>
<li><a href="template.php?page=page_two">Second content</a></li>
<li><a href="template.php?page=page_three">Third content</a></li>
(Or otherwise use $_SERVER["QUERY_STRING"]
. But you probably don't want to do that.)
Your third problem was using:
include('subfolder/folder/'.$_GET['$page'].'.html');
^^^ ^^^
You should have used just the $page
variable here, which you already read from $_GET
. Using that name as key again would not work. And you additionally used it ín single quotes (doubly wrong, but luckily without effect).
So correct would be:
$all_pages = array("main", "page_two", "page_three");
$page = $_GET['page'];
if ( in_array($page, $all_pages) )
{
include('subfolder/folder/'.$page.'.html');
}
Upvotes: 2