确保用户定义的路径在 PHP 中是安全的

发布于 2024-07-19 06:09:41 字数 635 浏览 6 评论 0原文

我正在 PHP 中实现一个简单的目录列表脚本。

我想在打开目录句柄并随意回显结果之前确保传递的路径是安全的。

$f = $_GET["f"];
if(! $f) {
    $f = "/";
}
// make sure $f is safe
$farr = explode("/",$f);
$unsafe = false;
foreach($farr as $farre) {
    // protect against directory traversal
    if(strpos($farre,"..") != false) {
        $unsafe = true;
        break;
    }
    if(end($farr) != $farre) {
        // make sure no dots are present (except after the last slash in the file path)
        if(strpos($farre,".") != false) {
            $unsafe = true;
            break;
        }
    }
}

这是否足以确保用户发送的路径是安全的,或者我还应该采取其他措施来防止攻击?

I am implementing a simple directory listing script in PHP.

I want to ensure that the passed path is safe before opening directory handles and echoing the results willy-nilly.

$f = $_GET["f"];
if(! $f) {
    $f = "/";
}
// make sure $f is safe
$farr = explode("/",$f);
$unsafe = false;
foreach($farr as $farre) {
    // protect against directory traversal
    if(strpos($farre,"..") != false) {
        $unsafe = true;
        break;
    }
    if(end($farr) != $farre) {
        // make sure no dots are present (except after the last slash in the file path)
        if(strpos($farre,".") != false) {
            $unsafe = true;
            break;
        }
    }
}

Is this enough to make sure a path sent by the user is safe, or are there other things I should do to protected against attack?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

养猫人 2024-07-26 06:09:41

realpath() 可能对您有帮助。

realpath() 展开所有符号链接
并解析对 '/./' 的引用,
中的 '/../' 和额外的 '/' 字符
输入路径,并返回
规范化绝对路径名。

但是,该函数假设所讨论的路径确实存在。 它不会对不存在的路径执行规范化。 在这种情况下,返回 FALSE。

It may be that realpath() is helpful to you.

realpath() expands all symbolic links
and resolves references to '/./',
'/../' and extra '/' characters in the
input path, and returns the
canonicalized absolute pathname.

However, this function assumes that the path in question actually exists. It will not perform canonization for a non-existing path. In this case FALSE is returned.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文