使用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个回答

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

dongxing2692
dongxing2692 谢谢,curl_setopt($ ch,CURLOPT_RETURNTRANSFER,true); 正是我的代码中缺少的!
2 年多之前 回复

You need to add the Content-Disposition and Content-Type. For non-curl downloading you would use the following:

<?
$file="/path/to/file" //file location
header('Content-Type: application/octet-stream');
header('Content-Disposition: attachment; filename="'.basename($file).'"');
header('Content-Length: ' . filesize($file));
readfile($file);
?>
立即提问
相关内容推荐