使用PHP发出HTTP / 2请求 [英] Make HTTP/2 request with PHP
问题描述
有没有一种方法可以强制PHP与另一台服务器建立HTTP2连接,以查看该服务器是否支持该服务器?
Is there a way to force PHP to make a HTTP2 connection to another server just to see if that server supports it?
我已经尝试过:
$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
But both ways give me a HTTP1.1 response if I use the following URL https://www.google.com/#q=apache+2.5+http%2F2
我正在从发送请求一个启用HTTP / 2 + SSL的域。我在做什么错?
I'm sending the request from a HTTP/2 + SSL enabled domain. What am I doing wrong?
推荐答案
据我所知,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.";
}
这篇关于使用PHP发出HTTP / 2请求的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!