I am making a basic PHP source viewer for my blog’s example code folder.
<?php
if (isset($_GET['file']))
{
header('Content-type: text/plain');
$filename = realpath($_GET['file']);
if (startsWith($filename, dirname(__FILE__)))
{
echo file_get_contents($filename);
}
}
function startsWith($haystack, $needle)
{
$length = strlen($needle);
return (substr($haystack, 0, $length) === $needle);
}
?>
Is what I have here sufficient that it will never allow a file outside the directory in which this script is located, or subdirectories of this script’s directory, to be viewed? I’m guessing there’s a better solution than startsWith too, for checking whether a path is a descendant of a particular directory?
It’s going to be safe, yes. The
realpathpart is what you have to do, and you are doing it. This code does what it’s supposed to just fine.