I have a PDF file in my server, and there is a PHP page to force download the PDF file after some credential validation such as password validation, but if the user able to know the direct link of the PDF file they manage to view/download it without go through the credential validation.
Is there any method to protect the PDF file being access via direct link like http://domain.com/mypdf.pdf?
Use this code...
The best way would be to protect that folder with htaccess
, as you have mentioned. So you put all PDFs in pdf/
folder, and in the same pdf
folder you put .htaccess
file:
RewriteEngine on
RewriteRule .* your-php-script.php
Now no files can be accessed by url in this folder. Every request to a file in this folder will return what your-php-script.php
script returns. 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);
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