Is there any way to simplify this case?

I have this PHP code argument

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.php'); break; ..... } 

Which works fine, but I have a lot of files (e.g. 190), and I would be interested to know if there is a way to get this thing to work a lot with something, so I do not need to do 190 cases. I thought I could use condtion in this case and maybe see if this file is present, and if so, display it, and if not, then maybe page 404, but I was not sure if this is a good way ... any ideas will help a lot

+8
directory loops php switch-statement
source share
7 answers

If it is not entered by the user, you can do it as

 $include = $parts[count($parts) - 1]; if ($include) { if (file_exists($_SERVER['DOCUMENT_ROOT'] . '/pages/'.$include.'.php')){ include $_SERVER['DOCUMENT_ROOT'] . '/pages/'.$include.'.php'; } } 

repeat, do not do this if $ include is populated with user input!

+4
source share

You can predefine the file names in the array, and then use in_array to check for the existence of the name:

 $files = array('restaurant_pos', 'retail_pos', ......); $file = $parts[count($parts) - 1]; if (in_array($file, $files)) { include($_SERVER['DOCUMENT_ROOT'] . "/pages/$file.php"); } 
+15
source share

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 safer, for example, you can remove slashes with $parts[count($parts) - 1]

+2
source share

Make sure the file exists, and then include it.

Please note that you SHOULD check the contents of $page to make sure that it does not include a path, such as /../../../../ , to try to read somewhere else on your file system if it must be entered by the user.

If you know, for example, that all your paths will be alphanumeric with underscores, you can do:

 $page = $parts[count($parts)] - 1; if (preg_match('/^[A-Z0-9_]+$/i', $page)) { // it okay, so include it. if (file_exists($_SERVER['DOCUMENT_ROOT'] . "/pages/$page.php") { include($_SERVER['DOCUMENT_ROOT'] . "/pages/$page.php"); } } 
+2
source share

Why not something like this?

 $include_file = $_SERVER['DOCUMENT_ROOT'] . '/pages/' . $parts[count($parts) - 1] . '.php'; if (file_exists( $include_file )) { include( $include_file ); } 
+1
source share
 if (file_exists($path = $_SERVER['DOCUMENT_ROOT'].'/pages/'.$parts[count($parts) - 1].'.php') { include $path; } 
+1
source share

Another approach would be to check if a given file really exists in a specific directory:

 $file = $_SERVER['DOCUMENT_ROOT'] . '/' . basename($parts[count($parts) - 1]) . '.php'; if (is_file($file)) include($file); 
+1
source share

All Articles