确保用户定义的路径在 PHP 中是安全的
我正在 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 echo
ing 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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
realpath()
可能对您有帮助。但是,该函数假设所讨论的路径确实存在。 它不会对不存在的路径执行规范化。 在这种情况下,返回 FALSE。
It may be that
realpath()
is helpful to you.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.