這篇文章主要介紹了淺談PHP發送HTTP請求的幾種方式,整理一下除了使用 cURL 外 PHP 發送 HTTP 要求的方式,有興趣的可以瞭解一下。
PHP 開發中我們常用 cURL 方式封裝 HTTP 要求,什麼是 cURL?
cURL 是一個用來傳輸資料的工具,支援多種協議,如在 Linux 下用 curl 命令列可以發送各種 HTTP 要求。PHP 的 cURL 是一個底層的庫,它能根據不同協議跟各種伺服器通訊,HTTP 協議是其中一種。
現代化的 PHP 開發架構中經常會用到一個包,叫做 GuzzleHttp,它是一個 HTTP 用戶端,也可以用來發送各種 HTTP 要求,那麼它的實現原理是什麼,與 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 中的一個 Question,可見 GuzzleHttp 並不依賴 cURL 庫,而支援多種發送 HTTP 要求的方式。
PHP 發送 HTTP 要求的方式
那麼這裡整理一下除了使用 cURL 外 PHP 發送 HTTP 要求的方式。
1.cURL
詳細方法:http://www.jb51.net/article/56492.htm
2.stream流的方式
stream_context_create 作用:建立並返回一個文本資料流並應用各種選項,可用於 fopen(), file_get_contents() 等過程的逾時設定、Proxy 伺服器、請求方式、頭資訊設定的特殊過程。
以一個 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;}
關於 PHP stream 的介紹文章:http://www.jb51.net/article/68891.htm
3.socket方式
使用通訊端建立串連,拼接 HTTP 報文發送資料進行 HTTP 要求。
一個 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);}?>
本文介紹了發送 HTTP 要求的幾種不同的方式。