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条)

报告相同问题?

悬赏问题

  • ¥15 乌班图ip地址配置及远程SSH
  • ¥15 怎么让点阵屏显示静态爱心,用keiluVision5写出让点阵屏显示静态爱心的代码,越快越好
  • ¥15 PSPICE制作一个加法器
  • ¥15 javaweb项目无法正常跳转
  • ¥15 VMBox虚拟机无法访问
  • ¥15 skd显示找不到头文件
  • ¥15 机器视觉中图片中长度与真实长度的关系
  • ¥15 fastreport table 怎么只让每页的最下面和最顶部有横线
  • ¥15 java 的protected权限 ,问题在注释里
  • ¥15 这个是哪里有问题啊?