php获取远程图片类实例

原创
2016-07-25 09:12:57 691浏览

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

  1. if ( ! defined('basepath')) exit('no direct script access allowed');
  2. /*
  3. * 远程获取图片类
  4. *
  5. * 要求开启curl扩展
  6. * 模拟php上传原理,创建一个缓存目录,将远程获取的文件存放到缓存目录下。
  7. */
  8. class url_pic{
  9. protected $cache; //缓存路径
  10. public function __construct($cache='')
  11. {
  12. if(!emptyempty($cache))
  13. {
  14. $this->cache = $cache;
  15. }
  16. else
  17. {
  18. $this->cache = 'uploads/cache/';
  19. }
  20. }
  21. //设置缓存目录
  22. public function set_cache($cache='')
  23. {
  24. if(!emptyempty($cache))
  25. {
  26. $this->cache = $cache;
  27. }
  28. }
  29. /*
  30. * 获取远程图片 将文件存入cache文件夹
  31. *
  32. * $url 获取远程的文件的链接
  33. * $error
  34. * @return 777 则返回不能建立文件夹
  35. * @return 存入缓存的文件名
  36. */
  37. public function get_file($url,$error=777)
  38. {
  39. $path = $this->build_folder($this->cache);
  40. if($path==false) return $error;
  41. $curl = curl_init();
  42. // 设置你需要抓取的url
  43. curl_setopt($curl, curlopt_url, $url);
  44. // 设置header
  45. curl_setopt($curl, curlopt_header, 0);
  46. // 设置curl 参数,要求结果保存到字符串中还是输出到屏幕上。
  47. curl_setopt($curl, curlopt_returntransfer, 1);
  48. // 运行curl,请求网页
  49. $file = curl_exec($curl);
  50. // 关闭url请求
  51. curl_close($curl);
  52. //将文件写入获得的数据
  53. $filename = $this->cache.date("ymdhis");
  54. if(self::build_file($file, $filename)==false)
  55. {
  56. return false;
  57. }
  58. return $filename;
  59. }
  60. //建立文件夹
  61. public function build_folder($dir)
  62. {
  63. if (!is_dir($dir))
  64. {
  65. if (!mkdir($dir,0777,true) || !chmod($dir,0777))
  66. {
  67. return false;
  68. }
  69. }
  70. return true;
  71. }
  72. /*
  73. * 移动文件 模拟php的move_uploaded_file方法
  74. *
  75. * $cache 缓存文件路径
  76. * $filename 需要生成的文件名的绝对路径
  77. *
  78. * @return $filename
  79. */
  80. public function move_file($cache,$filename)
  81. {
  82. $file = @file_get_contents($cache);
  83. if(self::build_file($file, $filename)==false)
  84. {
  85. return false;
  86. }
  87. unlink($cache); //清除缓存图片
  88. return $filename;
  89. }
  90. /*
  91. * 生成文件
  92. * $file 需要写入的文件或者二进制流
  93. * $newname 需要生成的文件名的绝对路径
  94. */
  95. protected static function build_file($file,$filename)
  96. {
  97. $write = @fopen($filename,"w");
  98. if($write==false)
  99. {
  100. return false;
  101. }
  102. if(fwrite($write,$file)==false)
  103. {
  104. return false;
  105. }
  106. if(fclose($write)==false)
  107. {
  108. return false;
  109. }
  110. return true;
  111. }
  112. }
复制代码


声明:本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn核实处理。
上一条:php水仙花数的小例子 下一条:禁止页面缓存的几种方法

相关文章

查看更多