XSS 和 file_get_contents?

XSS and file_get_contents?

我的 url 就像 page.php?path=content/x/y/z/aaa.md。以下 php 代码是 XSS 安全的吗?

include "Parsedown.php";

function path_purifier($path) {
  if(substr($path, 0, 8) !== "content/")
    return null;
  if (strpos($path,'..') !== false)
    return null;
  return "./" . $path;
}

$parsedown = new Parsedown();
$path = $_GET['path'];
$path = path_purifier($path);
echo $parsedown->text(file_get_contents($path));

感谢您的关注

是的,看起来足够安全,但还不够完美。在调用 file_get_contents() 之前,您还需要调用 is_file() 并确保它 returns 为真。此外,为了使其更安全,您可以在其之上实施 CSRF 保护。

另外,请记住,一些托管服务提供商不允许相对路径。因此,如果像 '/content/x/y/file.md' 这样的路径可能在您的本地计算机上工作,请记住在某些主机上它不会。所以你最好总是使用绝对路径,比如 __DIR__ . '/content/x/y/file.md'