user1935676
user1935676

Reputation: 55

How to protect files from direct download?

I want to protect some files in my server from download but my site needs to have access in them. I want to protect some subtitles files, which are needed to be accessed by site, but I don't want anybody to download them. The site is hosted.

For example some sites use some strange strings that are connected with user, video and IP. Can be used something like this for my case.

http://www11.some-site.com:182/d/qygiatnqvsulzrqmk7n6nbhddbcscvyguy4auc3fn4nvf23jp64tjcpa/File-needed.mp4?start=0

Upvotes: 3

Views: 11234

Answers (2)

NaN
NaN

Reputation: 9094

If you are using Apache, You have to use rewrite rules in your .htaccess file. IF you are using other HTTP Server brand, you should use almost the same logic that I will show here, so check your HTTP server manual in that case.

Explain:

When you type www.me.com/index.php the PHP system puts the content generated by the echo commands you use inside your code.

When you type www.me.com/myfiles/iou345yo13i2u4ybo34ybu3/passwords.txt your server will put the file contents to the client browser, which will ask you to download it as a file or show as a page, depending of the file extension.

Now, if you do something like this in your .htaccess file:

 RewriteEngine On
 RewriteRule ^myfiles/([^/]*)^.pdf$ /index.php?file=$1& [L]
 # avoit direct access to your server directories file listing
 Options All -Indexes

You will type www.me.com/myfiles/file123.pdf but the server will execute index.php with the file name as content of the "file" parameter, and there in the code, you will be able to check the session to see if the user has the authorization to download this file.

If the user has the authorization, you then use the readfile() function to send the file to the user and he will not recognize where it came from (I mean the real path).

Look on how to do this here:

PHP - send file to user

Upvotes: 12

Daniel Afonso
Daniel Afonso

Reputation: 30

Change to 644 permissions in your content.

Upvotes: -4

Related Questions