ThinkingInBits
ThinkingInBits

Reputation: 11482

How can I allow only privledged users to download a pdf with php?

Lets say I have some pdf files stored on my server and I only want to allow a person who's paid have access to download a particular pdf.

So for an example, let's say I have a bunch of e-books. The only way a user would be able to download e-book A is if his account contains the right credentials for that particular book.

What's the best way to accomplish this?

Any ideas/advice on how to improve my idea are greatly appreciated!

My current idea:

Upvotes: 2

Views: 4351

Answers (3)

John Conde
John Conde

Reputation: 219924

1) Keep the PDFs located outside of your document root so no one can acess them directly through a browser

2) Have a PHP page serve up the PDF file so the only way to get to them is by being successfully logged in and verified and this is enforced on every download

Code for downloading file though PHP (please be sure to scrub input):

<?php
    $file_name = $_GET['filename']; // somefile.pdf
    $file = '/home/pathtofile/' . $file_name;

    header('Content-Description: File Transfer');
    header('Content-Type: application/octet-stream');
    header('Content-Disposition: attachment; filename=' . $file_name);
    header('Content-Transfer-Encoding: binary');
    header('Expires: 0');
    header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
    header('Pragma: public');
    header('Content-Length: ' . filesize($file));
    ob_clean();
    flush();
    readfile($file);
    exit;
?>

Upvotes: 4

timdev
timdev

Reputation: 62924

Store the PDFs outside the document root (if not possible because of some lame hosting setup, store them someplace hard to guess).

Check that the user has permission, and then do something like:

<?PHP
$pdf_path = '/some/dir/';
header('Content-type: application/pdf');
readfile($pdf_path . 'mydoc.pdf');

You might need to adjust the headers further, but that's the basic idea.

Upvotes: 1

Quasipickle
Quasipickle

Reputation: 4498

Store the PDFs below the document root. When someone wants to download say, A.pdf, direct them to a PHP page like: download.php?file=A.pdf. Write that download.php page to check the requesting user's privileges, and force a download of A.pdf if their privileges are good enough.

Upvotes: 4

Related Questions