Alexandru Vasilache
Alexandru Vasilache

Reputation: 1

Prevent direct access to a PDF on a PHP secured website

I created a PHP website with login and users have access to PDF files. How can I prevent unauthorized users from accessing the PDF files via direct link?

I tried with .htaccess but "deny from all allow from localhost" also blocks my logged users. I tried with RewriteEngine and it allows all even if i delete the line with empty referer :

# ultimate hotlink protection
<IfModule mod_rewrite.c>
 RewriteEngine on
 RewriteCond %{HTTP_REFERER}     !^$
 RewriteCond %{REQUEST_FILENAME} -f
 RewriteCond %{REQUEST_FILENAME} \.(gif|jpe?g?|png)$           [NC]
 RewriteCond %{HTTP_REFERER}     !^https?://([^.]+\.)?domain\. [NC]
 RewriteRule \.(gif|jpe?g?|png)$                             - [F,NC,L]
</ifModule>

What can I do?

Upvotes: 0

Views: 3188

Answers (2)

Carlos G&#243;mez
Carlos G&#243;mez

Reputation: 357

if all you want is that only login users can download a pdf file: In your html page, you put for example this link:

<a href:'download.php'>Download now!</a>

and then create a php file like this:

download.php

<?php 
session_start();
if(!isset($_SESSION["IdUser"])) {
    header("location:goToHell.php");
} 
else {
    $file="yourPath/theFile.pdf";

    if (file_exists($file)) {
        header('Content-Description: File Transfer');
        header('Content-Type: application/pdf');
        header('Content-Disposition: attachment; filename="'.basename($file).'"');
        header('Expires: 0');
        header('Cache-Control: must-revalidate');
        header('Pragma: public');
        header('Content-Length: ' . filesize($file));
        readfile($file);
        exit;
    }
}
?>

Upvotes: 1

anubhava
anubhava

Reputation: 785128

You can pdf in your blocked list:

# ultimate hotlink protection
<IfModule mod_rewrite.c>
 RewriteEngine on
 RewriteCond %{HTTP_REFERER}     !^$
 RewriteCond %{REQUEST_FILENAME} -f
 RewriteCond %{HTTP_REFERER}     !^https?://([^.]+\.)?domain\. [NC]
 RewriteRule \.(gif|jpe?g?|png|pdf)$ - [F,NC,L]
</ifModule>

However keep in mind that blocking based on HTTP_REFERER is not 100% secured as clients can send a custom HTTP_REFERER header also.

Upvotes: 0

Related Questions