• 欢迎访问搞代码网站,推荐使用最新版火狐浏览器和Chrome浏览器访问本网站!
  • 如果您觉得本站非常有看点,那么赶紧使用Ctrl+D 收藏搞代码吧

怎么php使用socket获取远程图片

php 搞代码 3年前 (2022-01-23) 12次浏览 已收录 0个评论

步骤:

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

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

3,构造HTTP请求并发送

4,读取HTTP响应并解析

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

代码实现如下:

<?php/* * 使用socket获取远程资源(网页,图片等) * url 资源URL * savepath 资源的保存路径 * return true/false */function get_remote_picture($url,$savepath="./"){    set_time_limit(0);    $pattern = '/(http:\/\/)?([^\/]+)(.+)/';    $res = preg_match($pattern, $url, $matches);    if($res == 0){        return false;    }    $host = "";//主机名    $file = "";//请求的文件    if(count($matches) == 3){        $host = $matches[1];        $file = $matches[2];    }else if(count($matches) == 4){        $host = $matches[2];        $file = $matches[3];    }else{        return false;    }    $socket = socket_create(AF_INET,SOCK_STREAM,SOL_TCP);    $res = socket_connect($socket,gethostbyname($host),80);    if(!$res){        //echo socket_strerror(socket_last_error($socket));        socket_close($socket);        return false;    }    $request = "";    $request .= "GET $file HTTP/1.1\r\n";    $request .= "Host: $host\r\n";    $request .= "Connection: close\r\n\r\n";    $len = socket_write($socket,$request);     $response = "";    while($buf=socket_read($socket,512)){        if(strlen($buf) == 0){            break;        }        $response .= $buf;    }    if(strpos($response,"\r\n\r\n")){        $arr = explode("\r\n\r\n",$response);        if(!file_exists($savepath)){            @mkdir($savepath);        }        $savepath = rtrim($savepath,'/').'/';        file_put_contents($savepath.basename($file),$arr[1]);    }else{        socket_close($socket);        return false;    }    socket_close($socket);    return true;} /* 获取百度logo */$url = "http://su.bdimg.com/static/superplus/img/logo_white.png";$result = get_remote_pict<strong>*本文来源gaodai#ma#com搞@代~码^网+</strong><strong>搞代gaodaima码</strong>ure($url);if($result){    echo 'get remote picture success';}else{    echo 'get remote picture failed';}

搞代码网(gaodaima.com)提供的所有资源部分来自互联网,如果有侵犯您的版权或其他权益,请说明详细缘由并提供版权或权益证明然后发送到邮箱[email protected],我们会在看到邮件的第一时间内为您处理,或直接联系QQ:872152909。本网站采用BY-NC-SA协议进行授权
转载请注明原文链接:怎么php使用socket获取远程图片

喜欢 (0)
[搞代码]
分享 (0)
发表我的评论
取消评论

表情 贴图 加粗 删除线 居中 斜体 签到

Hi,您需要填写昵称和邮箱!

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址