PHP + PDF,如何使用 curl 保存下载的 PDF?

标签 php pdf curl header save

欢迎

我在页面上保存下载的 pdf 时遇到了一点问题。要下载 pdf,我使用 Curl:

$CurlConnect = curl_init();
curl_setopt($CurlConnect, CURLOPT_URL, 'http://website.com/invoices/download/1');
curl_setopt($CurlConnect, CURLOPT_POST,   1);
curl_setopt($CurlConnect, CURLOPT_RETURNTRANSFER, 1 );
curl_setopt($CurlConnect, CURLOPT_POSTFIELDS, $request);
curl_setopt($CurlConnect, CURLOPT_USERPWD, $login.':'.$password);
$Result = curl_exec($CurlConnect);

现在在 $Result(string) 中我有所有 PDF 文件内容。现在开始我的问题。我想保存下载的 pdf:

header('Cache-Control: public'); 
header('Content-type: application/pdf');
header('Content-Disposition: attachment; filename="new.pdf"');
header('Content-Length: '.filesize($Result));
readfile($Result);

不幸的是,当我保存或打开一个新的 PDF 文件时,我得到一个空白文档。也许问题出在最后几行:

header('Content-Length: '.filesize($Result));
readfile($Result);

不幸的是,我不知道如何更改它们才能使其正常工作...我请求您的帮助。谢谢

最佳答案

两者都是filesizereadfile接受文件作为参数。您提供的是字符串而不是文件。

请试试这个。

$CurlConnect = curl_init();
curl_setopt($CurlConnect, CURLOPT_URL, 'http://website.com/invoices/download/1');
curl_setopt($CurlConnect, CURLOPT_POST,   1);
curl_setopt($CurlConnect, CURLOPT_RETURNTRANSFER, 1 );
curl_setopt($CurlConnect, CURLOPT_POSTFIELDS, $request);
curl_setopt($CurlConnect, CURLOPT_USERPWD, $login.':'.$password);
$Result = curl_exec($CurlConnect);

header('Cache-Control: public'); 
header('Content-type: application/pdf');
header('Content-Disposition: attachment; filename="new.pdf"');
header('Content-Length: '.strlen($Result));
echo $Result;

关于PHP + PDF,如何使用 curl 保存下载的 PDF?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15897264/

相关文章:

c - 使用 cURL 为自定义请求 header 发送空字符串值

php - 是否有与 Rails 迁移等效的 PHP?

PHP-MySql : Like Query with modified Table Column

javascript - PDF JavaScript : Function with a loop

javascript - 无法在 node.js 中代理 PDF 文件

php - Ghostscript pdf 到 jpg windows/linux 颜色差异

php - curl_getinfo 返回不存在站点的 HTTP 200 状态代码

PHP 和关键字

php - 使用 .htaccess 删除 php 扩展

c++ - 如何在 C++ 中使用 libcurl 发送和接收 POST 请求?