温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

php如何实现下载图片

发布时间:2021-03-11 10:06:46 来源:亿速云 阅读:130 作者:小新 栏目:编程语言

这篇文章主要介绍了php如何实现下载图片,具有一定借鉴价值,感兴趣的朋友可以参考下,希望大家阅读完这篇文章之后大有收获,下面让小编带着大家一起了解一下。

php实现下载图片的方法:1、使用“file_get_contents”实现下载图片;2、通过使用CURL实现下载图片;3、通过使用fopen实现下载图片即可。

PHP下载远程图片的几种方法总结

本文演示3个从远程URL下载图片,并保存到本地文件中的方法,包括file_get_contents,curl和fopen。

1、使用file_get_contents

function dlfile($file_url, $save_to)
{
 $content = file_get_contents($file_url);
 file_put_contents($save_to, $content);
}

2、使用CURL

function dlfile($file_url, $save_to)
{
 $ch = curl_init();
 curl_setopt($ch, CURLOPT_POST, 0); 
 curl_setopt($ch,CURLOPT_URL,$file_url); 
 curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); 
 $file_content = curl_exec($ch);
 curl_close($ch);
 $downloaded_file = fopen($save_to, 'w');
 fwrite($downloaded_file, $file_content);
 fclose($downloaded_file);
}

3、使用fopen

function dlfile($file_url, $save_to)
{
 $in=  fopen($file_url, "rb");
 $out=  fopen($save_to, "wb");
 while ($chunk = fread($in,8192))
 {
 fwrite($out, $chunk, 8192);
 }
 fclose($in);
 fclose($out);
}

下载与保存完整方法(输出日志那行可删除):

    private function downloadImage($url)
    {
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 30);
        $file = curl_exec($ch);
        curl_close($ch);
        $this->saveAsImage($url, $file);
    }
    private function saveAsImage($url, $file)
    {
        $filename = pathinfo($url, PATHINFO_BASENAME);
        $dirname = pathinfo(parse_url($url, PHP_URL_PATH), PATHINFO_DIRNAME);
        $path =  'public' . $dirname . '/';
        $fullpath =  'public' . $dirname . '/' . $filename;
        // 如果目录不存在,则创建
        if(!is_dir($path)) {
            mkdir($path, 0777, true);
        }
        if(file_exists($fullpath)) {
            //$this->output->writeln("【已存在】输出路径" . $fullpath);
        } else {
            $resource = fopen($fullpath, 'a');
            fwrite($resource, $file);
            fclose($resource);
            //$this->output->writeln("【已保存】输出路径" . $fullpath);
        }
    }

感谢你能够认真阅读完这篇文章,希望小编分享的“php如何实现下载图片”这篇文章对大家有帮助,同时也希望大家多多支持亿速云,关注亿速云行业资讯频道,更多相关知识等着你来学习!

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

php
AI