PHP:无需提供直接链接即可下载文件

我想要发票下载。 目前我使用简单的编号scheme(invoice-01.pdf,invoice-02.pdf等)。 我知道我可以使用散列来掩盖数据。

是否也可以使用PHP并通过不直接让用户指向它们来提供发票?

在php.net上甚至有这样的例子

<?php // We'll be outputting a PDF header('Content-type: application/pdf'); // It will be called downloaded.pdf header('Content-Disposition: attachment; filename="downloaded.pdf"'); // The PDF source is in original.pdf readfile('original.pdf'); ?> 

或者扩大一点

 <?php if ( can_this_file_be_downloaded() ) { header('Content-type: application/pdf'); header('Content-Disposition: attachment; filename="invoice.pdf"'); readfile("{$_GET['filename']}.pdf"); } else { die("None shall pass"); } ?> 

山姆有答案。 也把它们放在一个目录中.htaccess:

 Authname Private AuthType basic require user noadmittance 

如果他们知道这个url,那么他们就不能直接访问。 您仍然可以使用readfile()从您的PHP脚本中读取它。

我发现这个优秀的指南: 如何通过PHP服务大文件 。

特别有用的是lighttpd技巧 – 如果你的PHP恰好运行在lighhtpd下,脚本只需要设置“X-Sendfile”头文件,lighttpd会为你读取和发送文件(并且知道如何发送文件)。

更新:

Lighttpd有这个特性,Apache2有一个mod_xsendfile。

(引自NginX文档 )