php获取远程图片,php获取远程图片类实例

例子,一个php获取远程图片类。

代码:

复制代码 代码示例:

if ( ! defined('basepath')) exit('no direct script access allowed');

/*

* 远程获取图片类

*

* 要求开启curl扩展

* 模拟php上传原理,创建一个缓存目录,将远程获取的文件存放到缓存目录下。

*/

class url_pic{

protected $cache; //缓存路径

public function  __construct($cache='')

{

if(!emptyempty($cache))

{

$this->cache = $cache;

}

else

{

$this->cache = 'uploads/cache/';

}

}

//设置缓存目录

public function set_cache($cache='')

{

if(!emptyempty($cache))

{

$this->cache = $cache;

}

}

/*

* 获取远程图片 将文件存入cache文件夹

*

* $url 获取远程的文件的链接

* $error

* @return 777 则返回不能建立文件夹

* @return 存入缓存的文件名

*/

public function get_file($url,$error=777)

{

$path = $this->build_folder($this->cache);

if($path==false) return $error;

$curl = curl_init();

// 设置你需要抓取的url

curl_setopt($curl, curlopt_url, $url);

// 设置header

curl_setopt($curl, curlopt_header, 0);

// 设置curl 参数,要求结果保存到字符串中还是输出到屏幕上。

curl_setopt($curl, curlopt_returntransfer, 1);

// 运行curl,请求网页

$file = curl_exec($curl);

// 关闭url请求

curl_close($curl);

//将文件写入获得的数据

$filename = $this->cache.date("ymdhis");

if(self::build_file($file, $filename)==false)

{

return false;

}

return $filename;

}

//建立文件夹

public function build_folder($dir)

{

if (!is_dir($dir))

{

if (!mkdir($dir,0777,true) || !chmod($dir,0777))

{

return false;

}

}

return true;

}

/*

* 移动文件 模拟php的move_uploaded_file方法

*

* $cache 缓存文件路径

* $filename 需要生成的文件名的绝对路径

*

* @return $filename

*/

public function move_file($cache,$filename)

{

$file = @file_get_contents($cache);

if(self::build_file($file, $filename)==false)

{

return false;

}

unlink($cache); //清除缓存图片

return $filename;

}

/*

* 生成文件

* $file 需要写入的文件或者二进制流

* $newname 需要生成的文件名的绝对路径

*/

protected static function build_file($file,$filename)

{

$write = @fopen($filename,"w");

if($write==false)

{

return false;

}

if(fwrite($write,$file)==false)

{

return false;

}

if(fclose($write)==false)

{

return false;

}

return true;

}

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值