1

我希望从我的网络服务器下载带有下载进度信息的文件。为此,PHP cURL似乎是最佳选择。

但是,我遇到的困难是下载的文件没有放在Downloads文件夹中,通常会下载所有 Web 文件。我使用以下文件下载例程:

$fp = fopen(dirname(__FILE__) . 'uploaded.pdf', 'w+');
$url = "file:///D:/WEB/SAIFA/WWW/PickUpTest.pdf";    
$ch = curl_init(str_replace(" ","%20", $url));
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_USERAGENT, 'Mozilla/5.0 (Windows NT 6.1; rv:2.0.1) Gecko/20100101 Firefox/4.0.1');
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_BINARYTRANSFER, true);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
curl_setopt($ch, CURLOPT_BUFFERSIZE, 1024*8);
curl_setopt($ch, CURLOPT_NOPROGRESS, false );
curl_setopt($ch, CURLOPT_PROGRESSFUNCTION, 'progressCallback' );
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 0);
curl_setopt( $ch, CURLOPT_FILE, $fp );
curl_exec( $ch );
curl_close($ch);
fclose($fp);
unset($fp);

我的问题是,而不是下载文件夹,该文件被静默下载到我的 WWW 文件夹中,我的 PHP 脚本包括这个 cURL 所在的文件夹。我也没有得到文件下载另存为对话框。

为了强制另存为对话框,我在脚本的开头添加了以下标题:

header("Content-Disposition: attachment; filename=\"uploaded.pdf\"");
$fp = fopen(dirname(__FILE__) . 'uploaded.pdf', 'w+');
...

使用标题后,我得到“另存为”对话框,但是,该文件仍然与我的 PHP 脚本一起以静默方式下载到文件夹中。在“下载”文件夹中,保存了文件大小为 0 的文件“uploaded.pdf”。

我的问题是,如何使 PHP cURL 正确下载文件并将它们放入下载文件夹并提供另存为对话框?

我用:

  • WAMP
  • Windows 7的
  • PHP 版本 5.4.12
  • 卷曲版本 7.29.0
4

1 回答 1

2

By using the file functions you're actually asking your server to save the file so it makes sense that the results of the cURL call end up in your PHP folder.

What you really want, if I understand the problem, is to send the results of the cURL back to the browser. You're halfway there by sending the header(...) - which lets the user's browser know a file is coming and should be downloaded, the step you've missed is sending the cURL data with the header.

You could echo the contents of the file after you've saved it or, more efficiently (assuming you don't want an extra copy of the file), remove the code to save the file locally and remove the cURL option CURLOPT_RETURNTRANSFER. That will tell cURL to send the output directly so it will become the data for the download.

Hope that helps!

EDIT A simple example that grabs a local file (C:\test.pdf) and sends it to the user's browser (as uploaded.pdf).

<?php

header("Content-Disposition: attachment; filename=\"uploaded.pdf\"");
// Get a FILE url to my test document
$url = 'file://c:/test.pdf';    
$url= str_replace(" ","%20", $url);
$ch= curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_BINARYTRANSFER, true);
curl_exec( $ch );

curl_close ($ch); 

Hope that helps a bit more!

于 2013-10-27T08:59:29.887 回答