如何安全地使用 file_get_contents? [英] How to use file_get_contents safely?

查看:58
本文介绍了如何安全地使用 file_get_contents?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在为我博客的示例代码文件夹制作一个基本的 PHP 源代码查看器.

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);
}

?>

我这里的内容是否足以让该脚本所在目录或该脚本目录的子目录之外的文件无法被查看?我猜还有比 startsWith 更好的解决方案,用于检查路径是否是特定目录的后代?

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?

推荐答案

它会很安全,是的.realpath 部分是你必须做的,你正在做.这段代码完成了它应该做的事情.

It's going to be safe, yes. The realpath part is what you have to do, and you are doing it. This code does what it's supposed to just fine.

这篇关于如何安全地使用 file_get_contents?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆