Issue with incorrect filename downloading or saving pdf file using acrobat plugins

When we try to secure our pdf files from direct url access using .htacess, we then encounter the problem in incorrect file name of downloaded pdf file. This is just a small issue but to the client this is a big hassle renaming each downloaded pdf to the correct filename.

Solution
 
Just by including the url filename in the url like below will do the trick

www.wtfthiscode.com/secure.php/mypdfilename?key=hashkeytomypdffile


Simple example on how to secure your public pdf file

Since we can't directly transfer the files away from public folder and due to time constraints. We decided to settle with .htaccess
 
.htaccess

RewriteEngine on
RewriteCond %{HTTP_REFERER} !^http(s)?://(www\.)?wtfthiscode.com [NC]
RewriteRule \.(pdf)$ - [NC,F,L]


The rewrite rule prevents any direct access to pdf files where the .htaccess file is located. We put the .htaccess file in uploads directory. If you don't have problem with rewrite in your web server, accessing the url like below will be forbidden. Note: this includes any url with .pdf in the end

www.wtfthiscode.com/uploads/mypdffile.pdf

Instead, you will access the file with below. We pass the file name to secure.php, it will then fetch it for us

www.wtfthiscode.com/secure.php?pdf=mypdffile.pdf&someparams
www.wtfthiscode.com/secure.php?pdf=hashkeytomypdffile

secure.php

<?php
header('Content-type: application/pdf');
header('Content-Disposition: inline; filename="mypdffile.pdf");
header('Content-Transfer-Encoding: binary');
header('Accept-Ranges: bytes');
echo file_get_contents('
/pathto/mypdffile.pdf');
?>
 


Comments

Popular posts from this blog

Basic Authentication Using .htaccess In Wamp/Xampp Server

Prevent parent anchor tag to redirect when a child is clicked