我在表中使用 php/mysql,我有一个名为“PDF”的列。
每一行都有一个指向我的网络服务器上的 PDF 文件的路径,我正在使用以下 PHP 代码:
$sql="SELECT * from table1 where customer_sequence = '53' and invoice_number = '1234' and sequence = '7839' ";
$rs=mysql_query($sql,$conn) or die(mysql_error());
$result=mysql_fetch_Array($rs);
header('Content-disposition: attachment; filename=/path/to/file/'.$result["pdf"].'');
header('Content-type: application/pdf');
readfile('/path/to/file/'.$result["pdf"].'');
SQL 工作正常,但是一旦它尝试下载它就不会执行任何操作。
我也尝试过:
header("Location: /path/to/file/".$result["pdf"]."");
但仍然没有运气 - 有什么想法我能做什么吗?
最佳答案
好吧,我们来解决一下。 首先,您不应该在 header 中输出文件的完整路径。只需使用这个:
header('Content-disposition: attachment; filename='.$result["pdf"]);
该 header 中的 filename
只是告诉浏览器应该用来保存文件的文件名。
其次,readfile()
不会遵循粘贴 URL 时浏览器使用的路径。 readfile()
使用 DOCUMENT_ROOT
。有关更多信息,您可以阅读此答案,例如:Document Root PHP
编辑 您的代码应如下所示:
$sql="SELECT * from table1 where customer_sequence = '53' and invoice_number = '1234' and sequence = '7839' ";
$rs=mysql_query($sql,$conn) or die(mysql_error());
$result=mysql_fetch_Array($rs);
header('Content-disposition: attachment; filename='.$result["pdf"]);
header('Content-type: application/pdf');
readfile($_SERVER['DOCUMENT_ROOT'] . '/path/to/file/'.$result["pdf"]);
关于PHP/MySQL 下载文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15890717/