在 PHP 中防止目录遍历但允许路径 [英] Preventing Directory Traversal in PHP but allowing paths

查看:21
本文介绍了在 PHP 中防止目录遍历但允许路径的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个基本路径/whatever/foo/

I have a base path /whatever/foo/

$_GET['path'] 应该是相对于它的.

and $_GET['path'] should be relative to it.

但是如何在不允许目录遍历的情况下完成此操作(读取目录)?

However how do I accomplish this (reading the directory), without allowing directory traversal?

例如

/..|../

无法正确过滤.

推荐答案

嗯,一种选择是比较真实路径:

Well, one option would be to compare the real paths:

$basepath = '/foo/bar/baz/';
$realBase = realpath($basepath);

$userpath = $basepath . $_GET['path'];
$realUserPath = realpath($userpath);

if ($realUserPath === false || strpos($realUserPath, $realBase) !== 0) {
    //Directory Traversal!
} else {
    //Good path!
}

基本上,realpath() 将解析提供的实际硬物理路径的路径(解析符号链接、...///等)...所以如果真正的用户路径不是从真正的基本路径开始,它正在尝试进行遍历.请注意,realpath 的输出将没有任何虚拟目录",例如 ......

Basically, realpath() will resolve the provided path to an actual hard physical path (resolving symlinks, .., ., /, //, etc)... So if the real user path does not start with the real base path, it is trying to do a traversal. Note that the output of realpath will not have any "virtual directories" such as . or .....

这篇关于在 PHP 中防止目录遍历但允许路径的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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