PHP中是否有一种简单的方法来测试URL是否支持HTTP / 2?我尝试按HTTP/2 identification in the specs检查curl_setopt($curl, CURLOPT_HEADER, true)
中的连接升级或h2。有许多站点可以添加URL,它会告诉站点是否支持HTTP / 2。只是想知道他们是如何测试它的,以及是否可以在PHP中完成类似的事情。在命令行上,我可以执行$ curl -vso --http2 https://www.example.com/
答案 0 :(得分:15)
您的服务器和cURL的安装都需要支持HTTP / 2.0。之后,您可以发出正常的cURL请求并添加CURLOPT_HTTP_VERSION
参数,这将使cURL尝试发出HTTP / 2.0请求。之后,您必须检查请求中的Headers以检查服务器是否确实支持HTTP / 2.0。
示例:
$url = "https://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, // cURL will attempt to make an HTTP/2.0 request (can downgrade to HTTP/1.1)
]);
$response = curl_exec($ch);
现在您需要检查cURL是否确实发出了HTTP / 2.0请求:
if ($response !== false && strpos($response, "HTTP/2.0") === 0) {
echo "Server of the URL has HTTP/2.0 support."; // yay!
} elseif ($response !== false) {
echo "Server of the URL has no HTTP/2.0 support."; // nope!
} else {
echo curl_error($ch); // something else happened causing the request to fail
}
curl_close($ch);