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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With