Is there a way to simplify this case statement?
I have this PHP case statement
switch ($parts[count($parts) - 1]) {
case 'restaurant_pos':
include($_SERVER['DOCUMENT_ROOT'] . '/pages/restaurant_pos.php');
break;
case 'retail_pos':
include($_SERVER['DOCUMENT_ROOT'] . '/pages/retail_pos.p开发者_Go百科hp');
break;
.....
}
Which works great but I have many many files (like 190) and I would love to know if there is a way to make this case statement many work with anything so I dont have to do 190 case conditions. I was thinking I can use the condtion in the case and maybe see if that file is present and if so then display and if not then maybe a 404 page but i was not sure a good way to do this...any ideas would help alot
You can predefine file names in an array and then use in_array
in order to check name's existence:
$files = array('restaurant_pos', 'retail_pos', ......);
$file = $parts[count($parts) - 1];
if (in_array($file, $files)) {
include($_SERVER['DOCUMENT_ROOT'] . "/pages/$file.php");
}
If it's not user input, you can do it like
$include = $parts[count($parts) - 1];
if ($include) {
if (file_exists($_SERVER['DOCUMENT_ROOT'] . '/pages/'.$include.'.php')){
include $_SERVER['DOCUMENT_ROOT'] . '/pages/'.$include.'.php';
}
}
repeating, don't do this if $include is being filled from user's input !
This is a simple implementation without security checks:
$file=$_SERVER['DOCUMENT_ROOT']."/pages/".$parts[count($parts) - 1].".php";
if(file_exists($file)) include $file;
else show404();
To make it more secure for example you can remove slashes from $parts[count($parts) - 1]
Check that the file exists, and then include it.
Note that you MUST validate the contents of $page
to be sure it doesn't include a path like /../../../../
to attempt to read somewhere else on your filesystem if this is to be user input.
If you know, for example that all your paths will be alphanumeric with underscores, you could do:
$page = $parts[count($parts)] - 1;
if (preg_match('/^[A-Z0-9_]+$/i', $page)) {
// it's okay, so include it.
if (file_exists($_SERVER['DOCUMENT_ROOT'] . "/pages/$page.php") {
include($_SERVER['DOCUMENT_ROOT'] . "/pages/$page.php");
}
}
Why not something like this?
$include_file = $_SERVER['DOCUMENT_ROOT'] . '/pages/' . $parts[count($parts) - 1] . '.php';
if (file_exists( $include_file ))
{
include( $include_file );
}
if (file_exists($path = $_SERVER['DOCUMENT_ROOT'].'/pages/'.$parts[count($parts) - 1].'.php')
{
include $path;
}
Another approach would be to check if the given file really exists in a particular directory:
$file = $_SERVER['DOCUMENT_ROOT'] . '/' . basename($parts[count($parts) - 1]) . '.php';
if (is_file($file)) include($file);
精彩评论