dongrui6787 2014-08-03 04:44
浏览 180
已采纳

使用curl下载图像,成功运行但输出到浏览器

I am successfully using CURL to download images from a website, the thing is in the browser it is outputting the file contents; I just want it to download with no output at all.

My script is below, it involves a few different classes,

private function download($url, $basePath, $fileName) {

    // Base directory path
    $basePath = $_SERVER['DOCUMENT_ROOT'] . $basePath;
    // The directory does not yet exist
    if (!is_dir($basePath)) {
        // Create the directory
        mkdir($basePath, 0777, true);
    }
    // Create the file handle
    $f = fopen($basePath . $fileName, 'w');
    // Download the request
    $this->client->download(new Requests\RequestCustom($url), $f);
}

// CLIENT

public function download(AbstractRequest $request, $f) {

    // Initiate a new curl
    $ch = curl_init();
    // Set curl options
    curl_setopt_array($ch, [
        CURLOPT_URL => $request->getUrl(),
        CURLOPT_FILE => $f,
        CURLOPT_TIMEOUT => 99,
        CURLOPT_HEADER => false,
        CURLOPT_RETURNTRANSFER => true,
    ]);
    // Add file to file handles array
    $this->fileHandles[] = $f;
    // Add to curl multi download handle
    curl_multi_add_handle($this->curlMultiDownload, $ch);
}

// CLIENT DESTRUCTOR
public function __destruct() {

    // Close curl multi handle
    curl_multi_close($this->curlMulti);
    // Execute curl multi downloads
    do {
        curl_multi_exec($this->curlMultiDownload, $running);
        curl_multi_select($this->curlMultiDownload);
    } while ($running > 0);
    // Close each file
    foreach($this->fileHandles as $f) {
        fclose($f);
    }
    // Close curl multi download handle
    curl_multi_close($this->curlMultiDownload);
}

Like I said the images do download but I also get the output of them in the browser, some of which I posted below; it goes on for pages and pages.

�PNG IHDR���7~� pHYs�� OiCCPPhotoshop ICC profilexڝSgTS�=���BK���KoR RB���&*! J�!��Q�EEȠ�����Q,� ��!���������{�kּ������>��������H3Q5��B�������.@� $p�d!s�#�~<<+"��x��M��0���B�

Thanks,

展开全部

  • 写回答

2条回答 默认 最新

  • duandan1995 2014-08-16 14:39
    关注

    It is essential that in order for the RETURN_TRANSFER => true to work, it must be set before the curl CURLOPT_FILE is set.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)
编辑
预览

报告相同问题?

手机看
程序员都在用的中文IT技术交流社区

程序员都在用的中文IT技术交流社区

专业的中文 IT 技术社区,与千万技术人共成长

专业的中文 IT 技术社区,与千万技术人共成长

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

客服 返回
顶部