且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何在 PHP 中发送 HTTP/2 POST 请求

更新时间:2022-11-27 21:47:29

PHP >= 5.5.24 的 CURL 扩展支持 HTTP/2.(因为这次提交)

The CURL extension for PHP >= 5.5.24 has support for HTTP/2. (since this commit)

您还需要安装 libcurl(curl 函数使用的底层库)并启用 HTTP/2 支持.这意味着 libcurl 比 7.38.0 新,但实际上,越新越好.Libcurl 构建时必须明确启用 HTTP/2 支持,并在编译时使用 --with-nghttp2 标志.

You also need a libcurl installed — the underlying library that the curl functions use — with HTTP/2 support enabled. That means a libcurl newer than 7.38.0 but really, the newer the better. Libcurl has to have been built with HTTP/2 support explicitly enabled, using the --with-nghttp2 flag at compile time.

只需像平常一样使用 curl,并设置 CURLOPT_HTTP_VERSION 选项通过传入 CURL_HTTP_VERSION_2_0 来使用 HTTP/2.然后您将请求升级到版本 2 如果客户端和服务器都支持它.

Just use curl as you'd normally use it, and set the CURLOPT_HTTP_VERSION option to use HTTP/2 by passing in CURL_HTTP_VERSION_2_0. Then you'll get the request upgraded to version 2 if the client and server both support it.

在 PHP 5.5.24 之前,如果 libcurl 构建时支持 HTTP/2,您可以显式传入 CURL_HTTP_VERSION_2_0 的 int 值,因为 PHP 仍会将其传递给 libcurl.目前,它的值为 3——这不应该改变,但 可以.

Prior to PHP 5.5.24, if libcurl has been built with HTTP/2 support, you can pass in the int value of CURL_HTTP_VERSION_2_0 explicitly as PHP will still pass it through to libcurl. Currently, it has a value of 3 — this should not change, but could.

if (!defined('CURL_HTTP_VERSION_2_0')) {
    define('CURL_HTTP_VERSION_2_0', 3);
}

$ch = curl_init();
curl_setopt($ch, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_2_0);