DENY direct download of file using php

后端 未结 4 2210
情书的邮戳
情书的邮戳 2020-12-15 14:18

I have .doc and .zip files in download directory on my server. whoever visit my site page (download-file.php) only those user should

相关标签:
4条回答
  • 2020-12-15 14:25

    You should disallow access to your files directory, and offer downloads only PHP driven (example with PDFs):

    data/.htaccess (googled):

    deny from all
    

    download.php:

    /* User access check here, prior to the following code */
    
    $name = 'MyPDF.pdf';
    $filename = 'data/pdf_12345.pdf';
    header('Content-Disposition: attachment; filename="'.$name.'"');
    header("Content-Type: application/pdf");
    header("Content-Length: " . filesize($file));
    fpassthru($filename)
    

    Of course you can set different filenames for each user and each request, like download.php?file=MyPDF

    0 讨论(0)
  • 2020-12-15 14:27

    If you have a dedicated server the easiest and in my opinion the most secure way is to store the files outside of /var/www/

    You can for example create a folder /var/webdocs/ and store them there.

    0 讨论(0)
  • 2020-12-15 14:41

    You should be able to restrict people from directly accessing your content using a method similar to the following code:

    RewriteCond %{HTTP_REFERER} !^http://your_domain.com/.*$ [NC]

    RewriteCond %{HTTP_REFERER} !^http://your_domain.com$ [NC]

    RewriteCond %{HTTP_REFERER} !^http://www.your_domain.com/.*$ [NC]

    RewriteCond %{HTTP_REFERER} !^http://www.your_domain.com$ [NC]

    RewriteRule .*.(jpg|jpeg|gif|png|bmp|pdf|doc)$ http://your_domain.com/no_access.php [R,NC]

    This would prevent people from directly linking images, pdfs or docs from your site. Then, files with these extensions would only be able to accessed from your site. If someone attempts to directly link or access your files, they will experience the whatever you choose for them to see (that you place in the no_access.php).

    0 讨论(0)
  • 2020-12-15 14:51

    In the htaccess file in your document root, you can include these rules:

    RewriteEngine On
    # you can add whatever extensions you want routed to your php script
    RewriteCond %{REQUEST_URI} \.(doc|zip|pdf)$ [NC]
    RewriteRule ^(.*)$ /download-file.php?filename=$1 [L]
    

    Then in your download-file.php, you can display whatever you need to display and the download link, which your php script can just immediately serve the file using php's readfile() (see link for examples)

    0 讨论(0)
提交回复
热议问题