wkyip
wkyip

Reputation: 500

PHP - Protect PDF file being access by direct link

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?

Upvotes: 5

Views: 3115

Answers (1)

Bruce
Bruce

Reputation: 1681

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);

Upvotes: 4

Related Questions