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

时间:2014-08-03 12:44:41

标签: php curl

我成功使用CURL从网站下载图像,事情是在浏览器中输出文件内容;我只是想让它下载而根本没有输出。

我的脚本如下,它涉及几个不同的类,

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);
}

就像我说图像确实下载但我也在浏览器中得到了它们的输出,其中一些我在下面发布;它继续用于页面和页面。

PNGIHDR 7~ pHYSs OiCCPPhotoshopICCprofilexڝSgTS = BK KoRRB & *! J ! Q EEȠ Q, ! { kּ > H3Q5 B 。@ $p d!s # 〜<< +“ x M 0 B

谢谢,

2 个答案:

答案 0 :(得分:1)

为了使RETURN_TRANSFER => true能够正常工作,必须先设置,然后才能设置卷曲CURLOPT_FILE

答案 1 :(得分:0)

您需要添加Content-Disposition和Content-Type。对于非卷曲下载,您将使用以下内容:

<?
$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);
?>
相关问题