PHP - protect access to PDF file by direct link

I have a PDF file on my server and there is a PHP page to force the PDF file to be downloaded after some credentials like password verification, but if the user can find out the direct link to the PDF file they will be able to view / download it without going through validation check.

Is there a way to protect access to the PDF file via a direct link like http://domain.com/mypdf.pdf ?

+3


source to share


1 answer


Use this code ...

The best way would be to protect this folder with htaccess

, as you mentioned. This way you put all PDF files in a folder pdf/

and in the same folder pdf

you put the file .htaccess

:

RewriteEngine on
RewriteRule .* your-php-script.php

      



Now no files are available by url in this folder. Every request for a file in that folder returns the result of the your-php-script.php

script. In your-php-script.php

you do something like this: -

//Check if user has right to access the file. If no, show access denied and exit the script.
$path = $_SERVER['REQUEST_URI'];
$paths = explode('/', path);
$lastIndex = count($paths) - 1;
$fileName = $paths[$lastIndex]; // Maybe add some code to detect subfolder if you have them
// Check if that file exists, if no show some error message
// Output headers here
readfile($filename);

      

+1


source







All Articles