PHP發送HTTP請求的幾種方式

(原文地址:https://blog.tanteng.me/2017/...php

副標題:cURL庫和Guzzle HTTP客戶端區別服務器

PHP 開發中咱們經常使用 cURL 方式封裝 HTTP 請求,什麼是 cURL?app

cURL 是一個用來傳輸數據的工具,支持多種協議,如在 Linux 下用 curl 命令行能夠發送各類 HTTP 請求。PHP 的 cURL 是一個底層的庫,它能根據不一樣協議跟各類服務器通信,HTTP 協議是其中一種。框架

現代化的 PHP 開發框架中常常會用到一個包,叫作 GuzzleHttp,它是一個 HTTP 客戶端,也能夠用來發送各類 HTTP 請求,那麼它的實現原理是什麼,與 cURL 有何不一樣呢?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.socket

這是 GuzzleHttp 文檔 FAQ 中的一個 Question,可見 GuzzleHttp 並不依賴 cURL 庫,而支持多種發送 HTTP 請求的方式。工具

PHP 發送 HTTP 請求的方式

那麼這裏整理一下除了使用 cURL 外 PHP 發送 HTTP 請求的方式。post

1.cURL

略過ui

2.stream流的方式

stream_context_create 做用:建立並返回一個文本數據流並應用各類選項,可用於 fopen(), file_get_contents() 等過程的超時設置、代理服務器、請求方式、頭信息設置的特殊過程。url

以一個 POST 請求爲例:

<?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 的介紹文章:https://www.oschina.net/trans...

3.socket方式

使用套接字創建鏈接,拼接 HTTP 協議字符串發送數據進行 HTTP 請求。

一個 GET 方式的例子:

<?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 請求的幾種不一樣的方式。

相關文章
相關標籤/搜索