PHP下载远程图片并保存到本地方法总结

这篇文章主要介绍了PHP下载远程图片并保存到本地方法总结的相关资料,需要的朋友可以参考下。

1.获取远程文件大小及信息的函数

  1. function getFileSize($url){
  2. $url = parse_url($url);
  3. if($fp = @fsockopen($url['host'],emptyempty($url['port'])?80:$url['port'],$error)){
  4. fputs($fp,"GET ".(emptyempty($url['path'])?'/':$url['path'])." HTTP/1.1\r\n");
  5. fputs($fp,"Host:$url[host]\r\n\r\n");
  6. while(!feof($fp)){
  7. $tmp = fgets($fp);
  8. if(trim($tmp) == ''){
  9. break;
  10. }else if(preg_match('/Content-Length:(.*)/si',$tmp,$arr)){
  11. return trim($arr[1]);
  12. }
  13. }
  14. return null;
  15. }else{
  16. return null;
  17. }
  18. }
  19. echo getFileSize(<a href="http://www.phpfensi.com/download/xml.rar">http://www.phpfensi.com/download/xml.rar</a>)

2.图片

  1. //记录程序开始的时间
  2. $BeginTime=getmicrotime();
  3. function GrabImage($url,$filename="") {
  4. if($url==""):return false;endif;
  5. if($filename=="") {
  6. $ext=strrchr($url,".");
  7. if($ext!=".gif" && $ext!=".jpg"):return false;endif;
  8. $filename=date("dMYHis").$ext;
  9. }
  10. ob_start();
  11. readfile($url);
  12. $img = ob_get_contents();
  13. ob_end_clean();
  14. $size = strlen($img);
  15. $fp2=@fopen($filename, "a");
  16. fwrite($fp2,$img);
  17. fclose($fp2);
  18. return $filename;
  19. }
  20. $img=GrabImage("http://www.phpfensi.com/images/_1978837_detector_ap100.jpg","");
  21. if($img):echo '<pre><img src="'.$img.'"></pre>';else:echo "false";endif;
  22. //记录程序运行结束的时间
  23. $EndTime=getmicrotime();
  24. //返回运行时间
  25. exit($EndTime-$BeginTime);

3.全文下载图片

  1. if(!emptyempty($saveremoteimg))
  2. {
  3. $body = stripslashes($body);
  4. $img_array = array();
  5. preg_match_all("/(src|SRC)=[\"|'| ]{0,}(http:\/\/(.*)\.(gif|jpg|jpeg|bmp|png))/isU",$body,$img_array);
  6. $img_array = array_unique($img_array[2]);
  7. set_time_limit(0);
  8. $imgUrl = $img_dir."/".strftime("%Y%m%d",time());
  9. $imgPath = $base_dir.$imgUrl;
  10. $milliSecond = strftime("%H%M%S",time());
  11. if(!is_dir($imgPath)) @mkdir($imgPath,0777);
  12. foreach($img_array as $key =>$value)
  13. {
  14. $value = trim($value);
  15. $get_file = @file_get_contents($value);
  16. $rndFileName = $imgPath."/".$milliSecond.$key.".".substr($value,-3,3);
  17. $fileurl = $imgUrl."/".$milliSecond.$key.".".substr($value,-3,3);
  18. if($get_file)
  19. {
  20. $fp = @fopen($rndFileName,"w");
  21. @fwrite($fp,$get_file);
  22. @fclose($fp);
  23. }
  24. $body = ereg_replace($value,$fileurl,$body);
  25. }
  26. $body = addslashes($body);
  27. }

4.PHP远程文件下载类(支持断点续传)

1).功能:支持断点续传的下载,能计算传输率,能控制传输率

简易使用方法:

$object = new httpdownload();

$object->set_byfile($file);//服务器文件名,包括路径

$object->filename = $filename;//下载另存为的文件名

$object->download();

类文件:

  1. <?
  2. class httpdownload {
  3. var $data = null;
  4. var $data_len = 0;
  5. var $data_mod = 0;
  6. var $data_type = 0;
  7. var $data_section = 0; //section download
  8. var $sentSize=0;
  9. var $handler = array('auth' => null);
  10. var $use_resume = true;
  11. var $use_autoexit = false;
  12. var $use_auth = false;
  13. var $filename = null;
  14. var $mime = null;
  15. var $bufsize = 2048;
  16. var $seek_start = 0;
  17. var $seek_end = -1;
  18. var $totalsizeref = 0;
  19. var $bandwidth = 0;
  20. var $speed = 0;
  21. function initialize() {
  22. global $HTTP_SERVER_VARS;
  23. if ($this->use_auth) //use authentication {
  24. if (!$this->_auth()) //no authentication {
  25. header('WWW-Authenticate: Basic realm="Please enter your username and password"');
  26. header('HTTP/1.0 401 Unauthorized');
  27. header('status: 401 Unauthorized');
  28. if ($this->use_autoexit) exit();
  29. return false;
  30. }
  31. }
  32. if ($this->mime == null) $this->mime = "application/octet-stream"; //default mime
  33. if (isset($_SERVER['HTTP_RANGE']) || isset($HTTP_SERVER_VARS['HTTP_RANGE'])) {
  34. if (isset($HTTP_SERVER_VARS['HTTP_RANGE'])) $seek_range = substr($HTTP_SERVER_VARS['HTTP_RANGE'] , strlen('bytes='));
  35. else $seek_range = substr($_SERVER['HTTP_RANGE'] , strlen('bytes='));
  36. $range = explode('-',$seek_range);
  37. if ($range[0] > 0) {
  38. $this->seek_start = intval($range[0]);
  39. }
  40. if ($range[1] > 0) $this->seek_end = intval($range[1]);
  41. else $this->seek_end = -1;
  42. if (!$this->use_resume) {
  43. $this->seek_start = 0;
  44. //header("HTTP/1.0 404 Bad Request");
  45. //header("Status: 400 Bad Request");
  46. //exit;
  47. //return false;
  48. } else {
  49. $this->data_section = 1;
  50. }
  51. } else {
  52. $this->seek_start = 0;
  53. $this->seek_end = -1;
  54. }
  55. $this->sentSize=0;
  56. return true;
  57. }
  58. function header($size,$seek_start=null,$seek_end=null) {
  59. header('Content-type: ' . $this->mime);
  60. header('Content-Disposition: attachment; filename="' . $this->filename . '"');
  61. header('Last-Modified: ' . date('D, d M Y H:i:s \G\M\T' , $this->data_mod));
  62. if ($this->data_section && $this->use_resume) {
  63. header("HTTP/1.0 206 Partial Content");
  64. header("Status: 206 Partial Content");
  65. header('Accept-Ranges: bytes');
  66. header("Content-Range: bytes $seek_start-$seek_end/$size");
  67. header("Content-Length: " . ($seek_end - $seek_start + 1));
  68. } else {
  69. header("Content-Length: $size");
  70. }
  71. }
  72. function download_ex($size) {
  73. if (!$this->initialize()) return false;
  74. ignore_user_abort(true);
  75. //Use seek end here
  76. if ($this->seek_start > ($size - 1)) $this->seek_start = 0;
  77. if ($this->seek_end <= 0) $this->seek_end = $size - 1;
  78. $this->header($size,$seek,$this->seek_end);
  79. $this->data_mod = time();
  80. return true;
  81. }
  82. function download() {
  83. if (!$this->initialize()) return false;
  84. try {
  85. error_log("begin download\n", 3,"/usr/local/www/apache22/LOGS/apache22_php.err");
  86. $seek = $this->seek_start;
  87. $speed = $this->speed;
  88. $bufsize = $this->bufsize;
  89. $packet = 1;
  90. //do some clean up
  91. @ob_end_clean();
  92. $old_status = ignore_user_abort(true);
  93. @set_time_limit(0);
  94. $this->bandwidth = 0;
  95. $size = $this->data_len;
  96. if ($this->data_type == 0) //download from a file {
  97. $size = filesize($this->data);
  98. if ($seek > ($size - 1)) $seek = 0;
  99. if ($this->filename == null) $this->filename = basename($this->data);
  100. $res = fopen($this->data,'rb');
  101. if ($seek) fseek($res , $seek);
  102. if ($this->seek_end < $seek) $this->seek_end = $size - 1;
  103. $this->header($size,$seek,$this->seek_end); //always use the last seek
  104. $size = $this->seek_end - $seek + 1;
  105. while (!(connection_aborted() || connection_status() == 1) && $size > 0) {
  106. if ($size < $bufsize) {
  107. echo fread($res , $size);
  108. $this->bandwidth += $size;
  109. $this->sentSize+=$size;
  110. } else {
  111. echo fread($res , $bufsize);
  112. $this->bandwidth += $bufsize;
  113. $this->sentSize+=$bufsize;
  114. }
  115. $size -= $bufsize;
  116. flush();
  117. if ($speed > 0 && ($this->bandwidth > $speed*$packet*1024)) {
  118. sleep(1);
  119. $packet++;
  120. }
  121. }
  122. fclose($res);
  123. }
  124. elseif ($this->data_type == 1) //download from a string
  125. {
  126. if ($seek > ($size - 1)) $seek = 0;
  127. if ($this->seek_end < $seek) $this->seek_end = $this->data_len - 1;
  128. $this->data = substr($this->data , $seek , $this->seek_end - $seek + 1);
  129. if ($this->filename == null) $this->filename = time();
  130. $size = strlen($this->data);
  131. $this->header($this->data_len,$seek,$this->seek_end);
  132. while (!connection_aborted() && $size > 0) {
  133. if ($size < $bufsize) {
  134. $this->bandwidth += $size;
  135. $this->sentSize+=$size;
  136. } else {
  137. $this->bandwidth += $bufsize;
  138. $this->sentSize+=$bufsize;
  139. }
  140. echo substr($this->data , 0 , $bufsize);
  141. $this->data = substr($this->data , $bufsize);
  142. $size -= $bufsize;
  143. flush();
  144. if ($speed > 0 && ($this->bandwidth > $speed*$packet*1024)) {
  145. sleep(1);
  146. $packet++;
  147. }
  148. }
  149. } else if ($this->data_type == 2) {
  150. //just send a redirect header
  151. header('location: ' . $this->data);
  152. }
  153. if($this->totalsizeref==$this->sentSize )error_log("end download\n", 3,"/usr/local/www/apache22/LOGS/apache22_php.err");
  154. else error_log("download is canceled\n", 3,"/usr/local/www/apache22/LOGS/apache22_php.err");
  155. if ($this->use_autoexit) exit();
  156. //restore old status
  157. ignore_user_abort($old_status);
  158. set_time_limit(ini_get("max_execution_time"));
  159. }
  160. catch(Exception $e) {
  161. error_log("cancel download\n".$e, 3,"/usr/local/www/apache22/LOGS/apache22_php.err");
  162. }
  163. return true;
  164. }
  165. function set_byfile($dir) {
  166. if (is_readable($dir) && is_file($dir)) {
  167. $this->data_len = 0;
  168. $this->data = $dir;
  169. $this->data_type = 0;
  170. $this->data_mod = filemtime($dir);
  171. $this->totalsizeref = filesize($dir);
  172. return true;
  173. } else return false;
  174. }
  175. function set_bydata($data) {
  176. if ($data == '') return false;
  177. $this->data = $data;
  178. $this->data_len = strlen($data);
  179. $this->data_type = 1;
  180. $this->data_mod = time();
  181. return true;
  182. }
  183. function set_byurl($data) {
  184. $this->data = $data;
  185. $this->data_len = 0;
  186. $this->data_type = 2;
  187. return true;
  188. }
  189. function set_lastmodtime($time) {
  190. $time = intval($time);
  191. if ($time <= 0) $time = time();
  192. $this->data_mod = $time;
  193. }
  194. function _auth() {
  195. if (!isset($_SERVER['PHP_AUTH_USER'])) return false;
  196. if (isset($this->handler['auth']) && function_exists($this->handler['auth'])) {
  197. return $this->handler['auth']('auth' , $_SERVER['PHP_AUTH_USER'],$_SERVER['PHP_AUTH_PW']);
  198. } else return true; //you must use a handler
  199. }
  200. }
  201. ?>

5. php 使用GD库下载远程图片

  1. <?php
  2. $imgname = "http://imgdujia.kuxun.cn/newpic/929/812929/4.jpg";
  3. $src_im = imagecreatefromjpeg($imgname);
  4. $srcW = ImageSX($src_im); //获得图像的宽
  5. $srcH = ImageSY($src_im); //获得图像的高
  6. $dst_im = ImageCreateTrueColor($srcW,$srcH); //创建新的图像对象
  7. imagecopy($dst_im, $src_im, 0, 0, 0, 0, $srcW, $srcH);
  8. imagejpeg($dst_im, "newpic.jpg"); //创建缩略图文件
  9. echo "<img src="newpic.jpg" mce_src="newpic.jpg"></img>";
  10. ?>
  11. <?php
  12. header("Content-type: image/png");
  13. $im = imagecreatefromjpeg("http://postimg.mop.com/200602/02/74/122374/200602022335325121.JPG");
  14. $white = imagecolorallocate($im, 0xF9, 0xD7, 0xCD);
  15. imagefill($im, 0, 0,$white);
  16. $text_color = imagecolorallocate($im, 233, 14, 91);
  17. imagestring($im, 1, 5, 5, "A Simple Text String", $text_color);
  18. imagepng($im);
  19. imagedestroy($im);
  20. ?>

注意这个要把PHP分配内存调大,应用时用大内存服务器