PHP 開發(fā)中我們常用 cURL 方式封裝 HTTP 請求,什么是 cURL?
cURL 是一個(gè)用來傳輸數(shù)據(jù)的工具,支持多種協(xié)議,如在 Linux 下用 curl 命令行可以發(fā)送各種 HTTP 請求。PHP 的 cURL 是一個(gè)底層的庫,它能根據(jù)不同協(xié)議跟各種服務(wù)器通訊,HTTP 協(xié)議是其中一種。
現(xiàn)代化的 PHP 開發(fā)框架中經(jīng)常會(huì)用到一個(gè)包,叫做 GuzzleHttp,它是一個(gè) HTTP 客戶端,也可以用來發(fā)送各種 HTTP 請求,那么它的實(shí)現(xiàn)原理是什么,與 cURL 有何不同呢?
Does Guzzle require cURL?
No. Guzzle can use any HTTP handler to send requests. This means that Guzzle can be used with cURL, PHP's stream wrapper, sockets, and non-blocking libraries like React. You just need to configure an HTTP handler to use a different method of sending requests.
這是 GuzzleHttp 文檔 FAQ 中的一個(gè) Question,可見 GuzzleHttp 并不依賴 cURL 庫,而支持多種發(fā)送 HTTP 請求的方式。
PHP 發(fā)送 HTTP 請求的方式
那么這里整理一下除了使用 cURL 外 PHP 發(fā)送 HTTP 請求的方式。
1.cURL
詳細(xì)方法:http://www.jb51.net/article/56492.htm
2.stream流的方式
stream_context_create 作用:創(chuàng)建并返回一個(gè)文本數(shù)據(jù)流并應(yīng)用各種選項(xiàng),可用于 fopen(), file_get_contents() 等過程的超時(shí)設(shè)置、代理服務(wù)器、請求方式、頭信息設(shè)置的特殊過程。
以一個(gè) POST 請求為例:
PHP
<?php /** * Created by PhpStorm. * User: tanteng * Date: 2017/7/22 * Time: 13:48 */ function post($url, $data) { $postdata = http_build_query( $data ); $opts = array('http' => array( 'method' => 'POST', 'header' => 'Content-type: application/x-www-form-urlencoded', 'content' => $postdata ) ); $context = stream_context_create($opts); $result = file_get_contents($url, false, $context); return $result; }
關(guān)于 PHP stream 的介紹文章:http://www.jb51.net/article/68891.htm
3.socket方式
使用套接字建立連接,拼接 HTTP 報(bào)文發(fā)送數(shù)據(jù)進(jìn)行 HTTP 請求。
一個(gè) GET 方式的例子:
PHP
<?php $fp = fsockopen("www.example.com", 80, $errno, $errstr, 30); if (!$fp) { echo "$errstr ($errno)<br />\n"; } else { $out = "GET / HTTP/1.1\r\n"; $out .= "Host: www.example.com\r\n"; $out .= "Connection: Close\r\n\r\n"; fwrite($fp, $out); while (!feof($fp)) { echo fgets($fp, 128); } fclose($fp); } ?>
本文介紹了發(fā)送 HTTP 請求的幾種不同的方式。
以上就是本文的全部內(nèi)容,希望對大家的學(xué)習(xí)有所幫助,也希望大家多多支持。