PHP/MySQL 下载文件

标签 php mysql

我在表中使用 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/

相关文章:

javascript - 您可以阻止网站出现在浏览器的历史记录中吗?

python - pip install MySql-python==1.2.4 在 Ubuntu 12.04 上失败

mysql - 获取新插入元素或现有元素的最后一个 ID

php - 集成 php mysql 和 voip 以及文本到语音

php - git update-index --assume-unchanged 文件的 git pull 错误

php - 如何最好地存储用户信息和用户登录名和密码

php - 使用 PHP 和 MySQL 时如何搜索比常规内容更长的内容?

php - 将JSON数据发送到PHP并用它来操作MySQL

php - MODX Revo getCollection 的自定义排序顺序

php - 仅限于使用 PHP 标记的帖子