有關php發送HTTP請求方式介紹

來源:互聯網
上載者:User
這篇文章主要介紹了淺談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 要求的幾種不同的方式。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.