Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
873 views
in Technique[技术] by (71.8m points)

curl - Make HTTP/2 request with PHP

Is there a way to force PHP to make a HTTP2 connection to another server just to see if that server supports it?

I've tried:

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

And tried:

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

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

I'm sending the request from a HTTP/2 + SSL enabled domain. What am I doing wrong?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

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

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...