Does the file exist safely?
Of course not, especially if $page = "./configuration"
I would recommend replacing it with something like this:
$pages = array("blog", "home", "login");
if (in_array(strtolower($page), $pages))
include("pages/$page.php");
The EDIT: . You can create this list of valid pages using this code.
$pages = array();
if ($dh = opendir("pages")) {
while (($file = readdir($dh)) !== false) {
if (strstr($file, ".php") !== false) // make sure it is a .php file
$pages[] = substr($file, -4); // remove the .php
}
closedir($dh);
}
source to share
There is a typo in your code which I believe in. It should be:
if (file_exists("pages/$page.php")) {
include("pages/$page.php");
}
However, it leads to code injection, if PHP settings allow it, remote file inclusion.
You need to make sure that the page you include cannot be an arbitrary page.
Typically you will see this type of code in the "Loader" class using the Factory method, however in good implementations it restricts the files and classes it loads to a specific directory, or to a specific predefined set of files.
source to share
If $ page is never set, PHP will try to find that it can follow the variable_order directive inside your php.ini. This directive tells PHP about the search order for variables. Since the default is EGPCS for this, a cunning hacker then calls your script and tells you that it includes whatever file PHP has access to.
Example:
www.example.com/?page=dbConfig.ini
source to share
Storing all possible page names in an array is the safest approach, but you can also be reasonably safe by simply checking the supplied page name and ensuring that you don't have any "dangerous" files in your pages directory.
$page = basename($_GET['page']);
if (file_exists("pages/$page")) {
include("pages/$page");
} else {
include("pages/default.php");
}
source to share
Use basename ($ _ REQUEST ['page']) to prevent potential access to other directories and then check if it exists.
http://php.mirror.facebook.net/manual/en/function.basename.php
source to share
As ceejayoz said in bucabay's answer, the requested page could have had a "../" which allows the user to easily break out of where they should be. My answer to another question should serve you well.
fooobar.com/questions/2502299 / ...
If the link freezes: Basically you check the realpath () of the include directory and the requested file, if the realpath () of the file starts with the realpath () of the include directory, it can be included. (I used strpos () == 0 to check if the file path starts with the include path)
source to share