3

I wrote a small download script to hide the file path, the file "get_file.php" handles everything. next step I would like to disallow with htaccess all pdf-files from direct access trough the browser (if anybody knows the exact url to the file), but still provide access to the file with my "get_file.php".

I tried:

RewriteEngine on 
RewriteCond %{HTTP_REFERER} !^http://(www\.)?localhost [NC] 
RewriteCond %{HTTP_REFERER} !^http://(www\.)?localhost.*$ [NC] 
RewriteRule \.(pdf)$ - [F]

any ideas?

Amit Verma
  • 40,709
  • 21
  • 93
  • 115
Cycle99
  • 172
  • 1
  • 3
  • 16

3 Answers3

4

Try this rule at top of your .htaccess:

RewriteEngine on 

RewriteCond %{THE_REQUEST} \.pdf[?\s] [NC]
RewriteCond %{HTTP_REFERER} !^http://(www\.)?localhost [NC] 
RewriteRule ^ - [F]
anubhava
  • 761,203
  • 64
  • 569
  • 643
2

Just try this:

get_file.php

<?php
    // You can add extra codes to get your pdf file name here
    $file = 'file.pdf';

    if (file_exists($file)) {
        header('Content-Description: File Transfer');
        header('Content-Type: application/octet-stream');
        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;
    }
?>
akhilp2255
  • 330
  • 3
  • 13
2

1st step - htaccess - there are different ways I usually use FilesMatch:

<FilesMatch "\.pdf$">
    Order allow,deny
    Deny from all
</FilesMatch>

2nd step is at your PHP file - you have just to use local path to load it and display it.. /path/to/file.pdf Here are examples how to export it for the clients : correct PHP headers for pdf file download

Community
  • 1
  • 1
Svetoslav
  • 4,686
  • 2
  • 28
  • 43