curl 使用PHP进行HTTP/2请求

kx5bkwkv  于 12个月前  发布在  PHP
关注(0)|答案(1)|浏览(205)

有没有一种方法可以强制PHP与另一台服务器建立HTTP 2连接,看看该服务器是否支持它?
我试过了:

$options = stream_context_create(array(
               'http' => array(
                    'method' => 'GET',
                    'timeout' => 5,
                    'protocol_version' => 1.1
                )
              ));
$res = file_get_contents($url, false, $options);
var_dump($http_response_header);

字符串
并试图:

$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_HEADER, 1);
curl_setopt($ch, CURLOPT_NOBODY, 1);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_HTTP_VERSION, 3);
$response = curl_exec($ch);
var_dump($response);
curl_close($ch);


但如果我使用以下URL https://www.google.com/#q=apache+2.5+http%2F2,则这两种方式给予我一个HTTP 1.1响应
我正在从启用HTTP/2 + SSL的域发送请求。我做错了什么?

ej83mcc0

ej83mcc01#

据我所知,cURL是PHP中唯一支持HTTP 2.0的传输方法。“
您首先需要测试您的cURL版本是否支持它,然后设置正确的版本头:

if (
    defined("CURL_VERSION_HTTP2") &&
    (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 && str_starts_with($response, "HTTP/2")) {
        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.";
}

字符串

相关问题