php使用socket获取远程图片

来源:互联网 发布:淘宝平台费用是多少 编辑:程序博客网 时间:2024/05/20 10:11

步骤:

1,匹配URL中的主机名和文件部分

2,创建socket并连接到目标服务器

3,构造HTTP请求并发送

4,读取HTTP响应并解析

5,保存内容到文件并关闭socket连接


代码实现如下:

[php] view plaincopy
  1. <?php  
  2. /* 
  3.  * 使用socket获取远程资源(网页,图片等) 
  4.  * url 资源URL 
  5.  * savepath 资源的保存路径 
  6.  * return true/false 
  7.  */  
  8. function get_remote_picture($url,$savepath="./"){  
  9.     set_time_limit(0);  
  10.     $pattern = '/(http:\/\/)?([^\/]+)(.+)/';  
  11.     $res = preg_match($pattern$url$matches);  
  12.     if($res == 0){  
  13.         return false;  
  14.     }  
  15.     $host = "";//主机名  
  16.     $file = "";//请求的文件  
  17.     if(count($matches) == 3){  
  18.         $host = $matches[1];  
  19.         $file = $matches[2];  
  20.     }else if(count($matches) == 4){  
  21.         $host = $matches[2];  
  22.         $file = $matches[3];  
  23.     }else{  
  24.         return false;  
  25.     }  
  26.     $socket = socket_create(AF_INET,SOCK_STREAM,SOL_TCP);  
  27.     $res = socket_connect($socket,gethostbyname($host),80);  
  28.     if(!$res){  
  29.         //echo socket_strerror(socket_last_error($socket));  
  30.         socket_close($socket);  
  31.         return false;  
  32.     }  
  33.     $request = "";  
  34.     $request .= "GET $file HTTP/1.1\r\n";  
  35.     $request .= "Host: $host\r\n";  
  36.     $request .= "Connection: close\r\n\r\n";  
  37.     $len = socket_write($socket,$request);  
  38.   
  39.     $response = "";  
  40.     while($buf=socket_read($socket,512)){  
  41.         if(strlen($buf) == 0){  
  42.             break;  
  43.         }  
  44.         $response .= $buf;  
  45.     }  
  46.     if(strpos($response,"\r\n\r\n")){  
  47.         $arr = explode("\r\n\r\n",$response);  
  48.         if(!file_exists($savepath)){  
  49.             @mkdir($savepath);  
  50.         }  
  51.         $savepath = rtrim($savepath,'/').'/';  
  52.         file_put_contents($savepath.basename($file),$arr[1]);  
  53.     }else{  
  54.         socket_close($socket);  
  55.         return false;  
  56.     }  
  57.     socket_close($socket);  
  58.     return true;  
  59. }  
  60.   
  61. /* 获取百度logo */  
  62. $url = "http://su.bdimg.com/static/superplus/img/logo_white.png";  
  63. $result = get_remote_picture($url);  
  64. if($result){  
  65.     echo 'get remote picture success';  
  66. }else{  
  67.     echo 'get remote picture failed';  
  68. }  
0 0
原创粉丝点击