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

yipeiwu_com5年前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 安全过滤函数代码

复制代码 代码如下: //安全过滤输入[jb] function check_str($string, $isurl = false) { $string = preg_repl...

基于PHP magic_quotes_gpc的使用方法详解

PHP magic_quotes_gpc主要是作用在WEB客户服务端的,它的作用时间是从请求开始,接下来我们将具体的为大家讲解它的使用方式。AD:我们今天要向大家介绍的是PHP magi...

WordPress中用于获取文章信息以及分类链接的函数用法

get_post()(获取一篇文章) get_post() 函数可以根据 ID 查询一篇文章的信息,还能返回循环中的当前文章。 用法 get_post( $post, $output...

在Mac上编译安装PHP7的开发环境

在Mac上编译安装PHP7的开发环境

今天看到鸟哥发微博说php7 beta1测试版发布了,于是赶紧就去抢先下载,把自己的开发环境也升级到PHP7去,话不多少,下面就一起来搞起吧。。。 首先你得去官网下载php7 beta...

一个图片地址分解程序(用于PHP小偷程序)

如题,返回一个数组,可以获得图片地址的base url,相对地址,名称等,具体见下例: <? error_reporting(E_ALL ^ E_NOTICE); $...