I am trying to generate switch from list of files in directory
I have directory tree
../pages/
-home.php
-about.php
-service.php
-contact.php
../system/
-error404.php
-index.php
-functions.php
And I want to generate switch statement in function open_page() in functions.php to include file from PAGES into index.php.
What I need to generate is this function in functions.php:
open_page($page){
switch ($page) {
case '': require_once("pages/home.php"); break;
case 'home': require_once("pages/home.php"); break;
case 'about': require_once("pages/about.php"); break;
case 'service': require_once("pages/service.php"); break;
case 'contact': require_once("pages/contact.php"); break;
default: require_once("system/error404.php"); break;
}
}
My try:
//get all pages from dir PAGES
foreach (glob("pages/*.php") as $path) {
$file = explode("/", $path);
$filename = explode(".", $file[1]);
$pages[] = $filename[0];
}
switch ($page) {
case '': require_once("pages/home.php");
break;
foreach ($pages as $page){
case '{$page}': require_once ("pages/"{$page}".php");
}
default: require_once("system/error404.php");
break;
}
Thank you in advance.
EDIT:
index.php
<?php
include 'functions.php';
?>
<html>
<body>
<div id="menu">
<a href=index.php?page=home>Home</a>
<a href=index.php?page=about>About</a>
<a href=index.php?page=service>Service</a>
<a href=index.php?page=contact>Contact</a>
</div>
<div id="content">
<?php
open_page($_GET['page']);
?>
</div>
</body>
</html>
This isn't really an answer on how to do a loop in a switch but I believe you can solve your problem by doing this: You check to see if the file exists. If it does you load it. If not you load the error page.
function open_page($page = 'home') {
if (empty($page)) {
$page = 'home';
}
$file = "pages/{$page}.php"
if (file_exists($file)) {
require_once($file);
} else {
require_once("system/error404.php");
}
}
A switch is not required.
if($page=='')
$page = 'home';
$filename = "/path/to/{$page}.php";
if (file_exists($filename)) {
require_once($filename);
} else {
require_once("system/error404.php");
}
The logic is flawed for your switch
block.
You could do something like this instead:
$page = basename($page);
if(empty($page)) {
$page = "home";
}
if(file_exists("pages/{$page}.php")) {
require_once("pages/{$page}.php");
else {
require_once("pages/error404.php");
}
Edit : Notice how I used basename
around the $page
variable. This is fairly important so that your $page
can't be something like ../../some-other-file.php
, for example.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.