使用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);但它无法处理大文件,因为它首先读取内存。是否可以将文件直接流式传输到磁盘?
3 回答

一只斗牛犬
TA贡献1784条经验 获得超2个赞
<?php
set_time_limit(0);
//This is the file where we save the 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 file
curl_setopt($ch, CURLOPT_FILE, $fp);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
// get curl response
curl_exec($ch);
curl_close($ch);
fclose($fp);
?>

慕妹3242003
TA贡献1824条经验 获得超6个赞
我用这个方便的功能:
通过4094字节步骤下载它将无法满足您的记忆
function download($file_source, $file_target) { $rh = fopen($file_source, 'rb'); $wh = fopen($file_target, 'w+b'); if (!$rh || !$wh) { return false; } while (!feof($rh)) { if (fwrite($wh, fread($rh, 4096)) === FALSE) { return false; } echo ' '; flush(); } fclose($rh); fclose($wh); return true;}
用法:
$result = download('http://url','path/local/file');
然后,您可以检查一切是否正常:
if (!$result) throw new Exception('Download error...');
- 3 回答
- 0 关注
- 1860 浏览
添加回答
举报
0/150
提交
取消