1. 程式人生 > >PHP高效下載圖片儲存到本地

PHP高效下載圖片儲存到本地

 PHP如何怎麼樣高效下載圖片儲存到本地? 直接上程式碼:

/**
 * 下載圖片,儲存到本地檔案
 * 
 * @param string $url
 * @param string $saveFile
 * @return mixed
 */
function xiazai($url, $saveFile) {
    $parse = parse_url($url);
    if (!isset($parse['host'])) {
        return false;
    }

    $file = SAVE_PATH . $saveFile;
    echo 'Saving ', $file, PHP_EOL;

    mkdirs( dirname($file) );
    $ip = genRandIp();
    $fp = fopen($file, 'wb');

    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_FILE, $fp);
    curl_setopt($ch, CURLOPT_HEADER, 0);
    curl_setopt($ch, CURLOPT_HTTPHEADER, array(
        'CLIENT-IP:' . $ip,
        'X-FORWARDED-FOR:' . $ip,
        'User-Agent:Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/60.0.3100.0 Safari/537.36',
        'Host:' . $parse['host'],
    ));
    curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
    curl_setopt($ch, CURLOPT_TIMEOUT, 180);
    $res = curl_exec($ch);
    curl_close($ch);

    fclose($fp);

    // 下載失敗,則刪除空檔案
    if (filesize($file) <= 10) {
        @unlink($file);
        return false;
    }

    return $res;
}