如何在PHP中实现有限的文件访问?
我正在开发一个应用程序(LAMP),用户可以将文件上传到服务器,但不能与其他用户共享它的文件。所以,我的问题是实现一个安全机制,确保用户 A 无法访问用户 B 上传的文件。
我的方法是这样的:
- 每个用户都有一个用于存放其文件的文件夹 (/upload/userA)
- 添加一个 .htaccess 文件以重定向所有文件访问 PHP 脚本的 /upload 文件夹
- 检查用户是否有权访问子目录 (/userA)
您能看出这种方法有什么缺点吗?还有更好的选择吗?
I'm working on an application (LAMP) where users can upload files to the server but cannot share it's files with other users. So, my problem is to implement a secure mechanism that ensures user A cannot access to files uploaded by user B.
My approach is this:
- Each user has a folder for its files (/upload/userA)
- Add a .htaccess file to redirect all access to /upload folder to a PHP script
- Check if the user has permission to access to the subdirectory (/userA)
Can you see any drawback in this approach? Any better alternative?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您可以创建类似
download.php?id=1234
的内容,而不是对文件进行硬引用,只需从数据库中检查1234
用户是否有权下载该文件并根本不向用户显示物理路径。使用 HTTP 标头,您可以强制用户下载具有您所需文件名(存储在数据库中)的文件。允许用户直接从物理路径访问他们的文件并不是一个好主意,如果您尝试在每个请求上使用
.htaccess
进行挂钩,那么确实会更昂贵。大多数系统都会考虑生成一些随机字符串或 GUID,您不能通过随机更改字符来简单地访问其他人的文件。即在Facebook图片中,
../187170_697610597_4628627_q.jpg
有一个复杂的URL,用户可以直接访问,但无法通过更改几个数字来猜测另一个图像URL,这太难了,但不安全,不满足您的要求。Instead of making hard references to files, you can make something like
download.php?id=1234
and just check for1234
from database whether user has privileges to download the file and do not show the physical path to user at all.With HTTP headers, you can force users to download file with a filename you have desired (stored on database). Allowing users to directly access their files from physical paths is not a good idea and if you try to make a hook with
.htaccess
upon each request, that will be more expensive, indeed.Most systems consider generating some random strings or GUIDs that you can't simply access someone else's file by changing a character randomly. i.e. in Facebook images,
../187170_697610597_4628627_q.jpg
there is that complicated URL which users can directly access but can not guess another image URL by changing a few digits, that's too difficult but not safe and does not meet your requirements.