Page 1 of 1

PHP & Apache - How to protect downloads (such as PDFs)?

Posted: Wed May 17, 2006 12:27 pm
by techleet
Hi All,

Please forgive me if this is a tired subject!

I am running php4 on apache2. I secure all pages in the site with a combination of PHP and .htaccess. Here's my code:

.htaccess:

Code: Select all

AddType application/x-httpd-php .php .html
php_value auto_prepend_file /user/apache2/htdocs/include/php/header.php
header.php:

Code: Select all

<?php
session_start();
$permission=$_SESSION["permission"];
if(!$permission=="yes") {
   echo 'You are not allowed to access this page. Please access this page through our <a href="/index.php">Client Login Page</a>';
   echo '<script language="javascript" src="/include/javascript/logon_unsuccessful.js"></script>';
} 
?>
This works great for html docs, but what about downloads? How do I protect those?

Thanks! :D

Posted: Wed May 17, 2006 4:43 pm
by Nathaniel
Hmmm... add .pdf to your AddType application/x-httpd-php .php .html line

and in header.php, do something like

Code: Select all

if ( !$permission == "yes" )
{
//blah blah blah
}
else
{
//set the content-type to whatever the correct PDF type is... lookup the header() function
//readfile('the_pdf_file_that_should_be_in_a_non-public_directory.pdf');
}
Hope that helps, I'll expound on something if you need me to :)

Posted: Wed May 17, 2006 6:38 pm
by techleet
Nathaniel wrote:Hmmm... add .pdf to your AddType application/x-httpd-php .php .html line

and in header.php, do something like

Code: Select all

if ( !$permission == "yes" )
{
//blah blah blah
}
else
{
//set the content-type to whatever the correct PDF type is... lookup the header() function
//readfile('the_pdf_file_that_should_be_in_a_non-public_directory.pdf');
}
Hope that helps, I'll expound on something if you need me to :)
I think I follow you. The problem is, this would work for a pdf, but not for an html doc. This means I need two different header.php files; one to handle the html docs and one to handle the pdfs. I don't think .htaccess/auto_prepend_file can differentiate between file types that it's being attached to.

BUT

Your idea led me to another way to do this;

I put all pdfs in a non-public directory like you said, and link all pdfs downloads to a "download.php" file within a public directory. Point the link, like "<a href='download.php?myspecs.pdf'>LINK</a>". Have the download.php file include the redirect code (if !$permission), and do the readfile() from there using $_GET.

Thanks!