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

yipeiwu_com6年前PHP代码库

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);
}

感谢阅读,希望能帮助到大家,谢谢大家对本站的支持!

相关文章

PHP 事务处理数据实现代码

复制代码 代码如下:public function insertUser ($userArray){ foreach ($userArray as $key => $value)...

php禁止浏览器使用缓存页面的方法

本文实例讲述了php禁止浏览器使用缓存页面的方法。分享给大家供大家参考。具体方法如下: 页面缓存在有的时候是不需要的,我们可以禁止浏览器缓存页面。 在PHP中可以轻松的使用下面的语句实现...

PHP STRING 陷阱原理说明

A string is series of characters. String access and modification by character Characters with...

php xml 入门学习资料

起因:   今天做项目时遇到一个问题:需要动态更新主页上的图片,以示本站不是做完了就算了,是有人一直在维护。好了,需求有了,如何实现?!   我的想法如下:   图片存放位置:放在一个文...

php一些公用函数的集合

/*获得客户端ip地址*/     function getIP() {      &...