PHP发送HTTP请求的几种方式

文章来源:https://segmentfault.com/a/1190000010302052

 

记得刚来北京找工作的时候,有个面试题大概是问你知道通过php有哪几种方式发送http请求,当时自己填了个curl工具,也没写具体代码,考官直接说你这基本功很差,当时自己很羞愧,今天浏览别人的笔记,发现php发送http请求其实有三种方式,其中有名的GuzzleHttp工具包便支持多种发送 HTTP 请求的方式。

第一种

   curl工具

第二种

   stream流的方式,stream_context_create 作用:创建并返回一个文本数据流并应用各种选项,可用于 fopen(), file_get_contents() 等过程的超时设置、代理服务器、请求方式、头信息设置的特殊过程。

//stream流式
        $get = [
            'http'=>[
                'method'=>'get',
                'header'=>"Host: www.test.com\r\n"."Accept: */*\r\n"."Accept-Language: zh-CN,zh;q=0.9,sm;q=0.8\r\n\r\n"
            ]
        ];
        //
        $context = stream_context_create($get);
        $fp = fopen('http://www.test.com/thinkphp/public/index.php/index/index/index', 'r', false, $context); 
        fpassthru($fp); 
        fclose($fp); 

第三种

 socket方式,使用套接字建立连接,拼接 HTTP 协议字符串发送数据进行 HTTP 请求

//scoket方式
        $fp = fsockopen("www.test.com", 80, $errno, $errstr, 30);
        if (!$fp) {
            echo "$errstr ($errno)<br />\n";
        } else {
            $out = "GET /thinkphp/public/index.php/index/index/index HTTP/1.1\r\n";
            $out .= "Host: www.test.com\r\n";
            $out .= "Connection: Close\r\n\r\n";
            fwrite($fp, $out);
            while (!feof($fp)) {
                echo fgets($fp, 128).'</br>';
            }
            fclose($fp);
        }

 

看了人家的介绍,终于对php发送http请求方式有一个大致的了解了,当然,还有许多需要深入的地方,暂且当做知识点引子吧。

   

posted @ 2018-04-12 17:28  rcj_飞翔  阅读(151)  评论(0)    收藏  举报