通过curl_setopt()获取文件并将其写为.PNG

时间:2017-02-01 13:59:27

标签: php curl fwrite

我需要从.PNG下载的文件中创建一个curl_setopt()文件。
将创建.PNG,只有它才能被阅读 所以我的理由是,$rawdata没有正确的内容。

// Function to download a file (needed in one of the programming missions)
function htsGetFile($url, $filename) {
    $cookiefile = "cookie.txt";

    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_USERAGENT,'Mozilla/5.0');

    curl_setopt($ch, CURLOPT_AUTOREFERER, true);
    curl_setopt($ch, CURLOPT_REFERER, $url);
    curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);

    curl_setopt($ch, CURLOPT_COOKIEFILE, $cookiefile); // Cookiejar on creation, cookiefile on use

    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); // We need tot get the data back.
    curl_setopt($ch, CURLOPT_BINARYTRANSFER, true);

    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); //Will not check the ssl sertification.

    $rawdata = curl_exec($ch);

    if(file_exists($filename)){
        unlink($filename);
    }

    $fp = fopen($filename, 'wb');
    fwrite($fp, $rawdata);
    fclose($fp);

    if(curl_errno($ch)) {
        return false;
    } else {
        return $rawdata;
    }
    curl_close ($ch);
}




$username = "*******";
$password = "*******";

$url = "https://www.domain/path/";
$file = "download.png";    

if (htsLogin($username, $password))
    if (htsGetHTML($url) !== false)
        if (htsGetFile($url, $file) !== false)
            $img = htsGetFile($url, $file);
        else
            echo 'Getting file went wrong.';
    else
        echo 'Getting page went wrong.';
else
    echo 'Can\'t login.';

1 个答案:

答案 0 :(得分:0)

尝试使用file_put_contents($file_name, $rawdata)代替

$fp = fopen($filename, 'wb');
fwrite($fp, $rawdata);
fclose($fp);
两种变体中的

base64_encode($rawdata)