PHP中如何限制对目录及其子目录的访问?
您好,我正在 PHP 上制作某种文件资源管理器,例如,如果我有一个像这样的根文件夹:
/ (root)
|
|
|---home
|
|
|---user
|
|
|---folder
|
|---folder1
|
|---file1
现在我将如何做 user
将只能浏览其中的文件/home/user/ 并且无法执行例如 cd ../../
并走出去?多谢 :) 这是我用于 cd 命令的代码:
<?php
function cd($actualdir, $dir) {
//echo $actualdir.$dir."<br>";
if($dir == "..") {
$expdir = explode("/", $actualdir);
$newdir = array_pop($expdir);
$fulldir = "";
foreach($expdir as $value) {
$fulldir .= $value."/";
}
$fulldir = substr($fulldir, 0, -1);
if($fulldir == "./rootfs/home") {
return "permission denied";
} else {
return $fulldir;
}
} else {
if(file_exists($actualdir."/".$dir)) {
//echo $dir;
return $actualdir."/".$dir;
} else {
return "no";
}
}
}
?>
顺便说一句,根目录只是 Web 服务器根目录上的一个目录,它应该充当 shell 的系统根目录
编辑:基本上,如果用户是user
,则只允许他进入/home/user
及其子目录。如果用户test
仅访问/home/test
及其子目录。就这样
Hi I'm making some kind of file explorer on PHP and I'd like for example if I have a root folder like this:
/ (root)
|
|
|---home
|
|
|---user
|
|
|---folder
|
|---folder1
|
|---file1
Now how I would do so user
would be only able to browse files inside /home/user/ and would not be able to do for example cd ../../
and go outside? Thanks a lot :)
This is the code I use for the cd
command:
<?php
function cd($actualdir, $dir) {
//echo $actualdir.$dir."<br>";
if($dir == "..") {
$expdir = explode("/", $actualdir);
$newdir = array_pop($expdir);
$fulldir = "";
foreach($expdir as $value) {
$fulldir .= $value."/";
}
$fulldir = substr($fulldir, 0, -1);
if($fulldir == "./rootfs/home") {
return "permission denied";
} else {
return $fulldir;
}
} else {
if(file_exists($actualdir."/".$dir)) {
//echo $dir;
return $actualdir."/".$dir;
} else {
return "no";
}
}
}
?>
BTW The root dir is just a directory on the web server root that should act as the system root for the shell
EDIT: Basically, if the user is user
only allow him to enter to /home/user
and its subdirectories. If the user is test
only to /home/test
and subdirectories. That's all
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您可以使用 realpath($fulldir) 让文件系统解析相对路径(如..和符号链接)。
You could use realpath($fulldir) to let the filesystem resolve relative paths (like .. and symbolic links).
最后结束了这样做:
Finally ended doing this:
最简单的解决方案?不要让用户实际上浏览您的文件系统。如果它是文档上传应用程序或类似应用程序,请在数据库中表示它。
因此,您将拥有数据库中表示的目录(类别)以及每个类别的文件(项目)。
The simplest solution? Don't let users actually navigate your file system. Represent it in the database if it's a document-uploading app or similar.
So you would have directories (categories) represented in a database, and files (items) for each category.