dongrui6787 2014-08-03 12: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 22: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条)

报告相同问题?

悬赏问题

  • ¥100 Jenkins自动化部署—悬赏100元
  • ¥15 关于#python#的问题:求帮写python代码
  • ¥20 MATLAB画图图形出现上下震荡的线条
  • ¥15 关于#windows#的问题:怎么用WIN 11系统的电脑 克隆WIN NT3.51-4.0系统的硬盘
  • ¥15 perl MISA分析p3_in脚本出错
  • ¥15 k8s部署jupyterlab,jupyterlab保存不了文件
  • ¥15 ubuntu虚拟机打包apk错误
  • ¥199 rust编程架构设计的方案 有偿
  • ¥15 回答4f系统的像差计算
  • ¥15 java如何提取出pdf里的文字?