为了账号安全,请及时绑定邮箱和手机立即绑定

使用curl下载大文件

使用curl下载大文件

PHP
德玛西亚99 2019-08-02 15:39:42
使用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);

?>


查看完整回答
反对 回复 2019-08-02
?
慕妹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...');


查看完整回答
反对 回复 2019-08-02
  • 3 回答
  • 0 关注
  • 1860 浏览

添加回答

举报

0/150
提交
取消
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号