Does anyone know if code like this accessess b.php or c.php $test = "a"; if ($test == "a") include("a.php"); if ($test == "b") include("b.php"); if ($test == "c") include("c.php"); PHP: I'm wondering because I have a ton of BIG includes that I may only need to access if a certain variable is present. I know that even though they won't execute (because of the if statement), PHP may still grab the contents, right? And that takes server power, right?
If the variable determines which file to include you could do this: include($test.".php"); PHP: Even if it doesn't, you can still do this: $filename=""; switch($test) {case "xyz": $filename="somefile"; break; case "abc": $filename="another"; break; case "jsc": $filename="blahblah"; break; ... ... .. case "xxx": $filename="lastfile"; break; } include($filename.".php"); PHP:
Yeah, if you wanted to feel safer, you could just do one include statement and choose the appropriate name like plog suggested. But if an IF statement is not executed then none of the code in it is executed so include() is never called and the contents are never pulled and no server power is used prefetching all the includes.
This is the easiest and most secure way: switch($_GET["page"]) { case "contact": include 'contact.php'; break; case "info": include 'info.php'; break; case "products": include 'products.php'; break; default: include 'default.php'; } Code (markup): Lets say for the examples u guys mentioned, what if someone enters "lalalal" in the url via get method? This way the default part in switch will assure that the default (index) page will be shown.
Or... include("./pages/" . (file_exists("./pages/" . $_GET['page'] . ".php") ? $_GET['page'] : "default") . ".php"); PHP: One line. Yes, I realize that is a big security risk, though. They could crawl your directories like that. So here's a function to fix it: function IsSafeInclude($x) { if(strpos($x, "/../") !== false || strpos($x, "../") === 0 || strpos($x, "/..") == (strlen($x) - 3) || $x == '..') return false; else return true; } include("./pages/" . (file_exists("./pages/" . $_GET['page'] . ".php") && IsSafeInclude($_GET['page']) ? $_GET['page'] : "default") . ".php"); PHP: If you're using a method like page inclusion based on what's in the URL, I'd recommend storing the pages in a separate folder like "pages" like I assumed in the code above. Nothing wrong with your Switch statement, it's secure enough, I just don't like having to add a line or so to it every time I want to add a new page.