<?php if($page = $_GET['page']){ if(file_exists("./pages/$page.php")){ include("./pages/$page.php"); }else{ include("404.php"); } }else{ include("pages/root.php"); } ?>I never comment my code because I think adding comments makes it look messy. But here's what this script does.
<?phpSimple? Start PHP... Duh
if($page = $_GET['page']){We use an if statement to make sure that there is something in the ?page=name but if there isn't, then we'll sort it out later. We set a variable named $page which is what is put in our url (of ?page=name so, $page would equal name.)
if(file_exists("./pages/$page.php")){If the page we're calling for in http://www.domain.com/pages/name.php exists, then we do...
include("./pages/$page.php");We include that page.
}else{Else if it doesn't exist.
include("404.php");We don't have the page so we send in a 404 page.
}Aww such a loner This stops the else statement.
}else{This else is for the if statement we did earlier for the $_GET['page'] - so if we can't get it. then we do...
include("pages/root.php");We include our main page for the content, I have it as root, others would be along the lines of news.php or something.
} ?>We end the last else and stop php.
Now for some notices...
Why is this very secure? Well I've seen a lot of dynamic php links that don't include the page as include("pages/$page.php"); - notice that "pages/" that we have there. This means that all of our pages that we want to include will be in a folder called pages.
But why is that secure you ask? Well I never used to add that extra folder in this kind of script, and my site was hacked due to that, site was banned by the host because of it, and also one of the servers on the host crashed due to the hacker using a PHP Hacking Script which he included into the page using that method. Doing it like that you're allowing anyone to add any page into your site. Not secure.
But they can't add a page of theirs into your site using this method because it's not in our pages folder.
So how do you do your links?
<a href="index.php?page=pagename">Page name</a>
What about a folder inside this pages folder?
<a href="index.php?page=foldername/pagename">Page Name</a>
Simple as that. And very secure and saves you so much more time than adding a load of case, include, break.