我想从this link下载pdf文件。从页面中选择每周摘要,我要下载第一个pdf。
PDF每周摘要 - 上周:按内部人员排序
我正在使用以下代码尝试下载pdf,
<?php
$file="https://www.sedi.ca/sedi/SVTWeeklySummaryACL?name=W1ALLPDFI&locale=en_CA";
if (file_exists($file))
{
if (FALSE!== ($handler = fopen($file, 'r')))
{
header('Content-Description: File Transfer');
header('Content-Type: application/octet-stream');
header('Content-Disposition: attachment; filename='.basename($file));
header('Content-Transfer-Encoding: chunked'); //changed to chunked
header('Expires: 0');
header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
header('Pragma: public');
//header('Content-Length: ' . filesize($file)); //Remove
//Send the content in chunks
while(false !== ($chunk = fread($handler,4096)))
{
echo $chunk;
}
}
exit;
}
echo "<h1>Content error</h1><p>The file does not exist!</p>";
?>
好像我无法使用PHP下载。我可以自己下载确认弹出窗口。有什么建议吗?
我也试过curl,还是无法下载。文件大小为零。<?php
$file="https://www.sedi.ca/sedi/SVTWeeklySummaryACL?name=W1ALLPDFI&locale=en_CA";
$path = 'c:\download\output.pdf';
$ch = curl_init($file);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$data = curl_exec($ch);
curl_close($ch);
file_put_contents($path, $data);
?>
答案 0 :(得分:10)
不要让你的PHP服务器充当代理,而不仅仅是:
<?PHP
$file="https://www.sedi.ca/sedi/SVTWeeklySummaryACL?name=W1ALLPDFI&locale=en_CA";
header("Location: $file");
?>
第2版
<?PHP
$file="https://www.sedi.ca/sedi/SVTWeeklySummaryACL?name=W1ALLPDFI&locale=en_CA";
header('Content-type: application/pdf');
header('Content-Disposition: attachment; filename="filename.pdf"');
readfile($file);
?>
第3版
curl_setopt($ch, CURLOPT_REFERER, 'https://www.sedi.ca/sedi/SVTWeeklySummaryACL?name=W1ALLPDFI&locale=en_CA');
将此行添加到原始代码中?
答案 1 :(得分:9)
最后,我可以使用PHP curl和CURLOPT_REFERER设置下载PDF文件。以下是代码。
<?php
$url = 'https://www.sedi.ca/sedi/SVTWeeklySummaryACL?name=W1ALLPDFI&locale=en_CA';
$path = "/pdf/output.pdf";
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_REFERER, 'https://www.sedi.ca/sedi/SVTReportsAccessController?menukey=15.03.00&locale=en_CA');
$data = curl_exec($ch);
curl_close($ch);
$result = file_put_contents($path, $data);
if(!$result){
echo "error";
}else{
echo "success";
}
&GT;
答案 2 :(得分:1)
另外,如上所述:
Download a image from SSL using curl?
对于https,我们应该添加以下内容:
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);