Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP - Protect PDF file being access by direct link

Tags:

php

pdf

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?

like image 279
wkyip Avatar asked Sep 27 '22 14:09

wkyip


1 Answers

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);
like image 152
Bruce Avatar answered Oct 31 '22 06:10

Bruce