php远程连接http方式
以下这三者是通过GET方式来获取数据
1、socket 方式
一般是指定网址、端口号、超时时间。
再对报头进行修改以及传递参数,包括:header、method、content,
返回的内容包括header报头。
python的httplib库,php的fsockopen的实现方式与此相同。
$dhost = "wx.upsmate.com"; $dport = 80; $params = "/cgi-bin/getuserlistpage/?access_token=V_5305328e3e107bd2893666052ea16437"; $fp = fsockopen($dhost, $dport, $errno, $errstr, 5); if (!$fp) { echo "$errstr ($errno)<br />\n"; } else { $out = "GET $params HTTP/1.1\r\n"; $out .= "Host: $dhost\r\n"; $out .= "Content-Type: application/x-www-form-urlencoded\r\n"; $out .= "Connection: Close\r\n\r\n"; fwrite($fp, $out); $response_data = ""; while (!feof($fp)) { $response_data .= fgets($fp, 128); } // echo substr($response_data, strpos($response_data,"\r\n\r\n")+4); echo $response_data; $fp1 = fopen("tmp1.php","w"); fwrite($fp1, $response_data); fclose($fp1); fclose($fp); }
2、文件流方式
fopen、file_get_contents这两种方式,两者最主要的区别在于:fopen可以一行行读取,而file_get_contents是一次性获取全部内容到一个字符串内。
两者都可以使用stream_context_create()创建资源流。而资源流的作用是:超时设置、代理服务器、请求方式、头信息设置这四个方面。
$opts = array( 'http'=>array( 'method'=>"GET", 'timeout'=>5, ) ); $context = stream_context_create($opts); $url = "http://wx.upsmate.com/cgi-bin/getuserlistpage/?access_token=V_5305328e3e107bd2893666052ea16437"; $context = file_get_contents($url,false,$context); echo $context;
fopen方式:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 | <?php $timeout = array ( 'http' => array ( 'timeout' => 5 //设置一个超时时间,单位为秒 ) ); $ctx = stream_context_create( $timeout ); if ( $fp = fopen ( "http://example.com/" , "r" , false, $ctx )) {<br> <br> $data = "" ; while (! feof ( $fp )) { $data .= fread ( $fp ,4196); } fclose( $fp ); } ?> |
file_get_contents post数据样例:
<? $data = array("name" => 'tim',"content" => 'test'); $data = http_build_query($data); $opts = array( 'http'=>array( 'method'=>"POST", 'header'=>"Content-type: application/x-www-form-urlencoded\r\n". "Content-length:".strlen($data)."\r\n" . "Cookie: foo=bar\r\n" . "\r\n", 'content' => $data, ) ); $cxContext = stream_context_create($opts); $sFile = file_get_contents("http://localhost/response.php", false, $cxContext); echo $sFile; ?>
参考网址:http://blog.csdn.net/heiyeshuwu/article/details/7841366
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· .NET Core 中如何实现缓存的预热?
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
· 基于Microsoft.Extensions.AI核心库实现RAG应用
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· Manus的开源复刻OpenManus初探
· AI 智能体引爆开源社区「GitHub 热点速览」
· 三行代码完成国际化适配,妙~啊~
· .NET Core 中如何实现缓存的预热?