How do I prevent public downloads of files using php?

允我心安 提交于 2019-11-30 03:23:04

问题


I have a script that allows only authorised users to upload files to a certain folder.

However I do not know how to prevent people from downloading freely without login.

I need the solution in php.

I have googled around but nothing straight forward as yet.

Currently in my document root I have a folder called admin and a subfolder called uploads inside the admin. So only admin role can upload. Both editor and admin can download. What should I do in this case?

Please advise.


回答1:


Put the files somewhere outside the public webroot directory, or configure your server to not serve the files. As long as your server will happily serve everything with a valid URL, there's nothing you can do with PHP to prevent that.


If your files are in the /public_html/ folder, take them out of that folder and place them in e.g. /secret_files/, so your directory structure looks something like this:

public_html/
    index.html
    admin/
        admin_index.php
secret_files/
    my_secret_file.txt

The webserver is only configured to serve files in the /public_html/ directory, so nobody will have access to directories outside (technical term above) it.

To still enable somebody to download those files, do as cletus suggests and use readfile to "manually serve" the files via a PHP script. PHP will still have access to these other parts of the file system, so you can use it as a gatekeeper.




回答2:


Don't store the files in a directory under the document root.

Instead move them somewhere else and then a PHP script can programmatically determine if someone can download them and then use readfile() or something similar to stream them to the user.

You could also configure the Web server to not serve files from this directory but then you need PHP to serve them anyway. It's cleaner simply not to put them under the document root.




回答3:


Answering question on how to password protect with PHP: This should solve your problem.



来源:https://stackoverflow.com/questions/2339649/how-do-i-prevent-public-downloads-of-files-using-php

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!