使用PHP发出HTTP / 2请求

时间:2016-05-10 14:00:47

标签: php curl http2

有没有办法强制PHP与另一台服务器建立HTTP2连接只是为了查看该服务器是否支持它?

我试过了:

$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);

但如果我使用以下网址https://www.google.com/#q=apache+2.5+http%2F2

,两种方式都会给我一个HTTP1.1响应

我从支持HTTP / 2 + SSL的域发送请求。我做错了什么?

1 个答案:

答案 0 :(得分:7)

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

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

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.";
}