PHP下載遠程文件到本地


此處以圖片為例:

方式一、

function download_image($pic_url)
{
    $time = time();
    $pic_local_path = dirname(__FILE__) . '/cache';
    //$pic_local = $pic_local_path . '/img1-' . $time . '.jpg';
    $pic_local = $pic_local_path . '/img1-' . $time . '.gif';

    if (!file_exists($pic_local_path)) {
        mkdir($pic_local_path, 0777);
        @chmod($pic_local_path, 0777);
    }

    ob_start(); //打開輸出
    readfile($pic_url); //輸出圖片文件
    $img = ob_get_contents(); //得到瀏覽器輸出
    ob_end_clean(); //清除輸出並關閉
    file_put_contents($pic_local, $img);
    return $pic_local;
}

$txt = download_image('http://sanplit.cn/wp-content/uploads/2019/05/002KAVNMgy6VjVbGRmMd8690.gif');
echo '第一張圖片:'.$txt.'<br />';

 

方式二、

$file = file_get_contents('http://sanplit.cn/wp-content/uploads/2019/05/002KAVNMgy6VjVbGRmMd8690.gif');
$time = time();
$pic_local_path = dirname(__FILE__) . '/cache';
$pic_local = $pic_local_path . '/img2-' . $time . '.jpg';

if (!file_exists($pic_local_path)) {
    mkdir($pic_local_path, 0777);
    @chmod($pic_local_path, 0777);
}
file_put_contents($pic_local, $file);

echo '第二張圖片:'.$pic_local.'<br />';

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM