PHP 下载远程网页图片并且保存在本地实例

我们要取远程服务器中网页的图片然后保存到我们本地需要珍到php fopen或curl等等这类的函数,下面我给大家介绍几个常用的实例.

fopen函数实例

ob_start:打开输出缓冲

readfile:读入一个文件并写入到输出缓冲

返回从文件中读入的字节数,如果出错返回 FALSE 并且除非是以 @readfile() 形式调用,否则会显示错误信息.

ob_get_contents : Return the contents of the output buffer(返回输出缓冲的内容)

This will return the contents of the output buffer without clearing it or FALSE, if output buffering isn’t active.(如果输出缓冲没有活动(打开),则返回 FALSE)

ob_end_clean() : Clean (erase) the output buffer and turn off output buffering(清除输出缓冲)

代码如下:

  1. <?php
  2. //URL是远程的完整图片地址,不能为空, $filename 是另存为的图片名字
  3. //默认把图片放在以此脚本相同的目录里
  4. function GrabImage($url,$filename=""){
  5. if($url == ""){
  6. return false;
  7. }
  8. $ext=strrchr($url,".");
  9. if($ext != ".gif" && $ext != ".jpg" && $ext != ".bmp" && $ext != ".png"){
  10. echo "格式不支持!";
  11. return false;
  12. }
  13. if($filename == ""){
  14. $filename = time()."$ext";
  15. }
  16. ob_start();
  17. readfile($url);
  18. $img=ob_get_contents();
  19. ob_end_clean();
  20. $size=strlen($img);
  21. $fp2=fopen($filename,"a");
  22. if(fwrite($fp2,$img) === false){
  23. echo "不能写入文件".$filename;
  24. exit();
  25. }else{
  26. echo "保存图片成功!";
  27. }
  28. fclose($fp2);
  29. return $filename;
  30. }
  31. //测试
  32. GrabImage("/logo.png","as.png");
  33. ?>

php下载远程图片函数,可伪造来路.

$gurl 要下载的图片地址

$rfurl 来路。如果目标图像做了防盗链设置,可以绕过。

$filename 下载图片保存的文件名,相对路径,不要用realpath

$gcookie 调整cookie 伪造的cookie

$JumpCount 跳转计数

$maxtime 最大次数

调用方法:

DownImageKeep(“http://www.baidu.com/img/baidu_jgylogo2.gif”,”http://baidu.com”,”a.gif”,”",0,10);

代码如下:

  1. function DownImageKeep($gurl, $rfurl, $filename, $gcookie=”", $JumpCount=0, $maxtime=30)
  2. {
  3. $urlinfos = GetHostInfo($gurl);
  4. $ghost = trim($urlinfos['host']);
  5. if($ghost==”)
  6. {
  7. return FALSE;
  8. }
  9. $gquery = $urlinfos['query'];
  10. if($gcookie==”" && !emptyempty($rfurl))
  11. {
  12. $gcookie = RefurlCookie($rfurl);
  13. }
  14. $sessionQuery = “GET $gquery HTTP/1.1rn”;
  15. $sessionQuery .= “Host: $ghostrn”;
  16. $sessionQuery .= “Referer: $rfurlrn”;
  17. $sessionQuery .= “Accept: */*rn”;
  18. $sessionQuery .= “User-Agent: Mozilla/4.0 (compatible; MSIE 5.00; Windows 98)rn”;
  19. if($gcookie!=”" && !preg_match(“/[rn]/”, $gcookie))
  20. {
  21. $sessionQuery .= $gcookie.”rn”;
  22. }
  23. $sessionQuery .= “Connection: Keep-Alivernrn”;
  24. $errno = “”;
  25. $errstr = “”;
  26. $m_fp = fsockopen($ghost, 80, $errno, $errstr,10);
  27. fwrite($m_fp,$sessionQuery);
  28. $lnum = 0;
  29. //获取应答头
  30. $m_httphead = Array();
  31. $httpstas = explode(” “,fgets($m_fp,256));
  32. $m_httphead["http-edition"] = trim($httpstas[0]);
  33. $m_httphead["http-state"] = trim($httpstas[1]);
  34. while(!feof($m_fp))
  35. {
  36. $line = trim(fgets($m_fp,256));
  37. if($line == “” || $lnum>100)
  38. {
  39. break;
  40. }
  41. $hkey = “”;
  42. $hvalue = “”;
  43. $v = 0;
  44. for($i=0; $i {
  45. if($v==1)
  46. {
  47. $hvalue .= $line[$i];
  48. }
  49. if($line[$i]==”:”)
  50. {
  51. $v = 1;
  52. }
  53. if($v==0)
  54. {
  55. $hkey .= $line[$i];
  56. }
  57. }
  58. $hkey = trim($hkey);
  59. if($hkey!=”")
  60. {
  61. $m_httphead[strtolower($hkey)] = trim($hvalue);
  62. }
  63. }
  64. if(preg_match(“/^3/”, $m_httphead["http-state"]))
  65. {
  66. if(isset($m_httphead["location"]) && $JumpCount<3) { $JumpCount++; DownImageKeep($gurl,$rfurl,$filename,$gcookie,$JumpCount); } else { return FALSE; } } if(!preg_match(“/^2/”, $m_httphead["http-state"])) { return FALSE; } if(!isset($m_httphead)) { return FALSE; } $contentLength = $m_httphead['content-length']; //保存图片 $fp = fopen($filename,”w”) or die(“写入文件:{$filename} 失败!”); $i=0; $okdata = “”; $starttime = time(); while(!feof($m_fp)) { $okdata .= fgetc($m_fp); $i++; //超时退出 if(time()-$starttime>$maxtime)
  67. {
  68. break;
  69. }
  70. //到达指定大小结束
  71. if($i >= $contentLength)
  72. {
  73. break;
  74. }
  75. }
  76. if($okdata!=”")
  77. {
  78. fwrite($fp,$okdata);
  79. }
  80. fclose($fp);
  81. if($okdata==”")
  82. {
  83. @unlink($filename);
  84. fclose($m_fp);
  85. return FALSE;
  86. }
  87. fclose($m_fp);
  88. return TRUE;
  89. }
  90. //获得网址的host和query部份
  91. function GetHostInfo($gurl)
  92. {
  93. $gurl = preg_replace(“/^http:///i”, “”, trim($gurl));
  94. $garr['host'] = preg_replace(“//(.*)$/i”, “”, $gurl);
  95. $garr['query'] = “/”.preg_replace(“/^([^/]*)//i”, “”, $gurl);
  96. return $garr;
  97. }
  98. //获得页面返回的Cookie信息
  99. function RefurlCookie($gurl)
  100. {
  101. global $gcookie,$lastRfurl;
  102. $gurl = trim($gurl);
  103. if(!empty($gcookie) && $lastRfurl==$gurl)
  104. {
  105. return $gcookie;
  106. }
  107. else
  108. {
  109. $lastRfurl=$gurl;
  110. }
  111. if(trim($gurl)==”)
  112. {
  113. return ”;
  114. }
  115. $urlinfos = GetHostInfo($gurl);
  116. $ghost = $urlinfos['host'];
  117. $gquery = $urlinfos['query'];
  118. $sessionQuery = “GET $gquery HTTP/1.1rn”;
  119. $sessionQuery .= “Host: $ghostrn”;
  120. $sessionQuery .= “Accept: */*rn”;
  121. $sessionQuery .= “User-Agent: Mozilla/4.0 (compatible; MSIE 5.00; Windows 98)rn”;
  122. $sessionQuery .= “Connection: Closernrn”;
  123. $errno = “”;
  124. $errstr = “”;
  125. $m_fp = fsockopen($ghost, 80, $errno, $errstr,10) or die($ghost.’
  126. ‘);
  127. fwrite($m_fp,$sessionQuery);
  128. $lnum = 0;
  129. //获取详细应答头
  130. $gcookie = “”;
  131. while(!feof($m_fp))
  132. {
  133. $line = trim(fgets($m_fp,256));
  134. if($line == “” || $lnum>100)
  135. {
  136. break;
  137. }
  138. else
  139. {
  140. if(preg_match(“/^cookie/i”, $line))
  141. {
  142. $gcookie = $line;
  143. break;
  144. }
  145. }
  146. }
  147. fclose($m_fp);
  148. return $gcookie;
  149. }