> 백엔드 개발 > PHP 튜토리얼 > php 利用socket发送GET,POST请求,socketget_PHP教程

php 利用socket发送GET,POST请求,socketget_PHP教程

WBOY
풀어 주다: 2016-07-13 09:45:39
원래의
929명이 탐색했습니다.

php 利用socket发送GET,POST请求,socketget

  作为php程序员一定会接触http协议,也只有深入了解http协议,编程水平才会更进一步。最近我一直在学习php的关于http的编程,许多东西恍然大悟,受益匪浅。希望分享给大家。本文需要有一定http基础的开发者阅读。

  今天给大家带来的是如何利用socket发送GET,POST请求。我借用燕十八老师封装好的一个Http类给进行说明。

  在日常编程中相信很多人和我一样大部分时间是利用浏览器向服务器提出GET,POST请求,那么可否利用其它方式提出GET,POST请求呢?答案必然是肯定的。了解过HTTP协议的人知道,浏览器提交请求的实质是向服务器发送一个请求信息,这个请求信息有请求行,请求头,请求体(非必须)构成。服务器根据请求信息返回一个响应信息。连接断开。

   HTTP请求的格式如下所示:

<span>1</span> <span><</span><span>request-line</span><span>></span>
<span>2</span> <span><</span><span>headers</span><span>></span>
<span>3</span> <span><</span><span>blank </span><span>line</span><span>></span>
<span>4</span> [<span><</span><span>request-body</span><span>></span>]
로그인 후 복사

  HTTP响应的格式与请求的格式十分相似:

<span><</span><span>status-line</span><span>></span>
<span><</span><span>headers</span><span>></span>
<span><</span><span>blank </span><span>line</span><span>></span><span>

[</span><span><</span><span>response-body</span><span>></span>]
로그인 후 복사

  我们可以利用HTTP发送请求的原理,可以重新考虑利用socket发送HTTP请求。

  Socket的英文原义是“孔”或“插座”。通常也称作“套接字”,用于描述IP地址和端口,是一个通信链的句柄,可以用来实现不同虚拟机或不同计算机之间的通信。在Internet上的主机一般运行了多个服务软件,同时提供几种服务。每种服务都打开一个Socket,并绑定到一个端口上,不同的端口对应于不同的服务。如此看来,其实利用socket操作远程文件和读写本地的文件一样容易,把本地文件看成通过硬件传输,远程文件通过网线传输就行了。

  因而可以将发送请求的考虑成 建立连接->打开socket接口(fsockopen())->写入请求(fwrite())->读出响应(fread()->关闭文件(fclose())。话不多说,直接上代码:

  

<?<span>php 

</span><span>interface</span><span> Proto {
    </span><span>//</span><span> 连接url</span>
    <span>function</span> conn(<span>$url</span><span>);

    </span><span>//</span><span>发送get查询</span>
    <span>function</span><span> get();

    </span><span>//</span><span> 发送post查询</span>
    <span>function</span><span> post();

    </span><span>//</span><span> 关闭连接</span>
    <span>function</span><span> close();
}



</span><span>class</span> Http <span>implements</span><span> Proto {

    </span><span>const</span> CRLF  = "\r\n"<span>;

    </span><span>protected</span> <span>$errno</span> = -1<span>;
    </span><span>protected</span> <span>$errstr</span> = ''<span>;
    </span><span>protected</span> <span>$response</span> = ''<span>;

    </span><span>protected</span> <span>$url</span> = <span>null</span><span>;
    </span><span>protected</span> <span>$version</span> = 'HTTP/1.1'<span>;
    </span><span>protected</span> <span>$fh</span> = <span>null</span><span>;
    
    </span><span>protected</span> <span>$line</span> = <span>array</span><span>();
    </span><span>protected</span> <span>$header</span> = <span>array</span><span>();
    </span><span>protected</span> <span>$body</span> = <span>array</span><span>();

    
    </span><span>public</span> <span>function</span> __construct(<span>$url</span><span>) {
        </span><span>$this</span>->conn(<span>$url</span><span>);
        </span><span>$this</span>->setHeader('Host: ' . <span>$this</span>->url['host'<span>]);
    }

    </span><span>//</span><span> 此方法负责写请求行</span>
    <span>protected</span> <span>function</span> setLine(<span>$method</span><span>) {
        </span><span>$this</span>->line[0] = <span>$method</span> . ' ' . <span>$this</span>->url['path'] . '?' .<span>$this</span>->url['query'] . ' '. <span>$this</span>-><span>version;
    }

    </span><span>//</span><span> 此方法负责写头信息</span>
    <span>public</span> <span>function</span> setHeader(<span>$headerline</span><span>) {
        </span><span>$this</span>-><span>header</span>[] = <span>$headerline</span><span>; 
    }

    </span><span>//</span><span> 此方法负责写主体信息</span>
    <span>protected</span> <span>function</span> setBody(<span>$body</span><span>) {
         </span><span>$this</span>->body[] = <span>http_build_query</span>(<span>$body</span><span>);
    }


    </span><span>//</span><span> 连接url</span>
    <span>public</span> <span>function</span> conn(<span>$url</span><span>) {
        </span><span>$this</span>->url = <span>parse_url</span>(<span>$url</span><span>);
        </span><span>//</span><span> 判断端口</span>
        <span>if</span>(!<span>isset</span>(<span>$this</span>->url['port'<span>])) {
            </span><span>$this</span>->url['port'] = 80<span>;
        }

        </span><span>//</span><span> 判断query</span>
        <span>if</span>(!<span>isset</span>(<span>$this</span>->url['query'<span>])) {
            </span><span>$this</span>->url['query'] = ''<span>;
        }

        </span><span>$this</span>->fh = <span>fsockopen</span>(<span>$this</span>->url['host'],<span>$this</span>->url['port'],<span>$this</span>->errno,<span>$this</span>->errstr,3<span>);
    }

    </span><span>//</span><span>构造get请求的数据</span>
    <span>public</span> <span>function</span><span> get() {
        </span><span>$this</span>->setLine('GET'<span>);
        </span><span>$this</span>-><span>request();
        </span><span>return</span> <span>$this</span>-><span>response;
    }

    </span><span>//</span><span> 构造post查询的数据</span>
    <span>public</span> <span>function</span> post(<span>$body</span> = <span>array</span><span>()) {      
        </span><span>$this</span>->setLine('POST'<span>);

        </span><span>//</span><span> 设计content-type</span>
        <span>$this</span>->setHeader('Content-type: application/x-www-form-urlencoded'<span>);
        
        </span><span>//</span><span> 设计主体信息,比GET不一样的地方</span>
        <span>$this</span>->setBody(<span>$body</span><span>);


        </span><span>//</span><span> 计算content-length</span>
        <span>$this</span>->setHeader('Content-length: ' . <span>strlen</span>(<span>$this</span>->body[0<span>]));

        </span><span>$this</span>-><span>request();

        </span><span>return</span> <span>$this</span>-><span>response;
    }

    </span><span>//</span><span> 真正请求</span>
    <span>public</span> <span>function</span><span> request() {
        </span><span>//</span><span> 把请求行,头信息,实体信息 放在一个数组里,便于拼接</span>
        <span>$req</span> = <span>array_merge</span>(<span>$this</span>->line,<span>$this</span>-><span>header</span>,<span>array</span>(''),<span>$this</span>->body,<span>array</span>(''<span>));
        </span><span>//</span><span>print_r($req);</span>

        <span>$req</span> = <span>implode</span>(self::CRLF,<span>$req</span><span>); 
        </span><span>//</span><span>echo $req; exit;</span>

        <span>fwrite</span>(<span>$this</span>->fh,<span>$req</span><span>);
        
        </span><span>while</span>(!<span>feof</span>(<span>$this</span>-><span>fh)) {
            </span><span>$this</span>->response .= <span>fread</span>(<span>$this</span>->fh,1024<span>);
        }

        </span><span>$this</span>->close(); <span>//</span><span> 关闭连接</span>
<span>    }


    </span><span>//</span><span> 关闭连接</span>
    <span>public</span> <span>function</span><span> close() {
        </span><span>fclose</span>(<span>$this</span>-><span>fh);
    }

}</span>
로그인 후 복사

利用此类发送一个简单的GET请求:

<?<span>php<br /><br />//记得引用Http类
</span><span>$url</span>="http://home.cnblogs.com/u/DeanChopper/"<span>;
</span><span>$http</span>=<span>new</span> Http(<span>$url</span><span>);


</span><span>$response</span>=<span>$http</span>-><span>get();

</span><span>print_r</span>(<span>$response</span>);
로그인 후 복사

  返回值为信息,可以对响应信息进行进一步处理,得到自己想得到的内容。

  

 

  

www.bkjia.comtruehttp://www.bkjia.com/PHPjc/1040167.htmlTechArticlephp 利用socket发送GET,POST请求,socketget 作为php程序员一定会接触http协议,也只有深入了解http协议,编程水平才会更进一步。最近我一直在...
관련 라벨:
원천:php.cn
본 웹사이트의 성명
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.
인기 튜토리얼
더>
최신 다운로드
더>
웹 효과
웹사이트 소스 코드
웹사이트 자료
프론트엔드 템플릿