我正在为我的博客的示例代码文件夹制作基本的PHP源代码查看器。如何安全地使用file_get_contents?
<?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);
}
?>
是我在这里充分的,它绝不允许在此脚本所在的目录,或该脚本的目录的子目录之外的文件,来看待?我猜测有比startWith更好的解决方案,用于检查路径是否是特定目录的后代?
但是'真实路径()'本身并不从本质上阻止因为他需要他的'startsWith()'函数来检查请求的文件是否在允许的目录中。但总而言之,解决方案似乎可以挽救。 – feeela
@feeela:'realpath'显然不会做这样的事 - 它不是函数描述的一部分。我想说的是'startsWith'检查是每个人都会想到的事情,但它本身并不安全*。它与'realpath'的组合使得它更安全。 – Jon