且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

使用PHP发出HTTP / 2请求

更新时间:2022-06-27 05:54:05

据我所知,cURL是PHP中唯一支持HTTP的传输方法2.0。

As far as I'm aware, cURL is the only transfer method in PHP that supports HTTP 2.0.

您首先需要测试您的cURL版本是否可以支持它,然后设置正确的版本标头:

You'll first need to test that your version of cURL can support it, and then set the correct version header:

if (curl_version()["features"] & CURL_VERSION_HTTP2 !== 0) {
    $url = "https://www.google.com/";
    $ch = curl_init();
    curl_setopt_array($ch, [
        CURLOPT_URL            =>$url,
        CURLOPT_HEADER         =>true,
        CURLOPT_NOBODY         =>true,
        CURLOPT_RETURNTRANSFER =>true,
        CURLOPT_HTTP_VERSION   =>CURL_HTTP_VERSION_2_0,
    ]);
    $response = curl_exec($ch);
    if ($response !== false && strpos($response, "HTTP/2") === 0) {
        echo "HTTP/2 support!";
    } elseif ($response !== false) {
        echo "No HTTP/2 support on server.";
    } else {
        echo curl_error($ch);
    }
    curl_close($ch);
} else {
    echo "No HTTP/2 support on client.";
}