1

Redirected from here, I need to prevent access of PDF (or any other) file types, when someone access it using direct URL.

The Problem

Say you had a PDF file that you’d like visitors on your own site to download.

However, if someone were to copy this link and call it from a browser window directly, or if they were to post the link to you PDF on another website then the document shall not be accessible. By default it is.

I am successful in hiding the pdf file path in address bar and the url formed is http://localhost/myproject/web/viewer.php?id=11&name=sample.pdf, but in console one can see the complete path like http://localhost/myproject/document/11/sample.pdf.

This code redirects successfully on second time page reload, but not when I select Open in new tab from console.

RewriteCond %{HTTP_REFERER} !^http://(www\.)?localhost [NC]
RewriteCond %{REQUEST_URI} !hotlink\.(pdf) [NC]
RewriteRule .*\.(pdf)$ http://google.com/ [NC]

Used below code in .htaccess to prevent access

RewriteEngine on 
RewriteCond %{HTTP_REFERER} !^http://(www\.)?localhost [NC] 
RewriteCond %{HTTP_REFERER} !^http://(www\.)?localhost.*$ [NC] 
RewriteRule \.(pdf)$ - [F]

Somehow it does not work accurately. It shows file forbidden message only if I hit CTRL+SHIFT+R key otherwise using the file URL I can still access it.

I want to prevent the pdf file showing as http://localhost/myproject/document/11/sample.pdf directly in the url bar

Community
  • 1
  • 1
Slimshadddyyy
  • 4,085
  • 5
  • 59
  • 121

2 Answers2

0

If you have access to a database, maybe you could store the file/s in a blob field. This way you can easily write code to protect the file how you like.

Mick
  • 1
  • 1
0

You can store PDF files not in webroot folder and return it content use PHP. For example for user URL will be like:

http://localhost/myproject/document.php?hash=some_hash`

and on file document.php you will get document hash from $_GET parametr use file_get_contents function. Also in this case you can allow access only once

I hope it will help

stepozer
  • 1,143
  • 1
  • 10
  • 22