猿问

使用curl下载大文件

使用curl下载大文件

我需要使用curl下载远程文件。


这是我的示例代码:


$ch = curl_init();

curl_setopt($ch, CURLOPT_URL, $url);

curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);


$st = curl_exec($ch);

$fd = fopen($tmp_name, 'w');

fwrite($fd, $st);

fclose($fd);


curl_close($ch);

但它无法处理大文件,因为它首先读取内存。


是否可以将文件直接流式传输到磁盘?


德玛西亚99
浏览 1861回答 3
3回答

一只斗牛犬

<?phpset_time_limit(0);//This is the file where we save the&nbsp; &nbsp; information$fp = fopen (dirname(__FILE__) . '/localfile.tmp', 'w+');//Here is the file we are downloading, replace spaces with %20$ch = curl_init(str_replace(" ","%20",$url));curl_setopt($ch, CURLOPT_TIMEOUT, 50);// write curl response to filecurl_setopt($ch, CURLOPT_FILE, $fp);&nbsp;curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);// get curl responsecurl_exec($ch);&nbsp;curl_close($ch);fclose($fp);?>

慕妹3242003

我用这个方便的功能:通过4094字节步骤下载它将无法满足您的记忆function&nbsp;download($file_source,&nbsp;$file_target)&nbsp;{ &nbsp;&nbsp;&nbsp;&nbsp;$rh&nbsp;=&nbsp;fopen($file_source,&nbsp;'rb'); &nbsp;&nbsp;&nbsp;&nbsp;$wh&nbsp;=&nbsp;fopen($file_target,&nbsp;'w+b'); &nbsp;&nbsp;&nbsp;&nbsp;if&nbsp;(!$rh&nbsp;||&nbsp;!$wh)&nbsp;{ &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;return&nbsp;false; &nbsp;&nbsp;&nbsp;&nbsp;} &nbsp;&nbsp;&nbsp;&nbsp;while&nbsp;(!feof($rh))&nbsp;{ &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;if&nbsp;(fwrite($wh,&nbsp;fread($rh,&nbsp;4096))&nbsp;===&nbsp;FALSE)&nbsp;{ &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;return&nbsp;false; &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;} &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;echo&nbsp;'&nbsp;'; &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;flush(); &nbsp;&nbsp;&nbsp;&nbsp;} &nbsp;&nbsp;&nbsp;&nbsp;fclose($rh); &nbsp;&nbsp;&nbsp;&nbsp;fclose($wh); &nbsp;&nbsp;&nbsp;&nbsp;return&nbsp;true;}用法:&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;$result&nbsp;=&nbsp;download('http://url','path/local/file');然后,您可以检查一切是否正常:&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;if&nbsp;(!$result) &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;throw&nbsp;new&nbsp;Exception('Download&nbsp;error...');
随时随地看视频慕课网APP
我要回答