
Originally Posted by
Dr Unne
You should never use user input to do anything that might affect or access anything on your computer. Otherwise people will pass your script a link like "http://...../?page=../../../etc/passwd" and then you're in trouble.
I'm no PHP expert, there may be better ways of doing this.
Code:
<?php
// By Samuraid
// Make a path safe(r) for inclusion
// Default page to load if no others are found
$default = 'defaultpage.php';
// Read the page path we need to include (don't rely on register_globals)
$in_path = (isset($_REQUEST['path'])) ? trim($_REQUEST['path']) : $default;
// Break the path at the slashes, and clean any invalid files that
// start with "." (so no one can hack paths or include hidden files)
$in_path = preg_split('#/#', str_replace('\\', '/', $in_path), -1, PREG_SPLIT_NO_EMPTY);
for ($i = 0, $ic = count($in_path); $i < $ic; $i++)
{
if ($in_path[$i][0] == '.')
{
unset($in_path[$i]);
}
}
// Recombine the cleaned path
$in_path = implode('/', $in_path);
// Build the full include path
$path_base = dirname(__FILE__) . '/';
// Check for recursive inclusion
if ($in_path == basename(__FILE__))
{
$in_path = $default;
}
// Read and output the file contents.
if (is_file($path_base . $in_path))
{
// Include the file
include $path_base . $in_path;
}
else
{
// File does not exist
print '<span style="color: red; font-weight: bold;">The file ' .
htmlspecialchars($in_path) . ' does not exist.</span>';
}
?>
P.S. Please report bugs.