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 />';

猜你喜欢

转载自www.cnblogs.com/sanplit/p/11120437.html
今日推荐