开发者

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

开发者 https://www.devze.com 2022-12-30 12:43 出处:网络
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.

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:

  • A user places an order

  • Upon success, a new folder would be created by their /account_num/order_id/ A copy of the particular file would be stored in this directory

  • Have php generate an .htaccess that would only allow access from a url that contains a random hash embedded into it.
  • The only way a user would be able to access this random hashed page is if they are signed in as the right 开发者_如何学Gouser, and the hash matches up with the hash stored in the database, otherwise they are redirected to home page.


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.


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


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号