OpenSwoole Hook Native CURL

Latest version: pecl install openswoole-26.11.1 | composer require openswoole/core:26.11.1

The OpenSwoole\Runtime::HOOK_NATIVE_CURL flag will enable coroutine support for the CURL library (libcurl). Support was added in OpenSwoole v4.6.0.

You must run --enable-hook-curl when you install OpenSwoole to enable CURL support. By enabling this it will automatically set the OpenSwoole\Runtime::HOOK_NATIVE_CURL flag and turn off SWOOLE_HOOK_CURL.

When using OpenSwoole\Runtime::HOOK_NATIVE_CURL it is enabled by default with SWOOLE_HOOK_ALL

Example

<?php

Co::set(['hook_flags' => OpenSwoole\Runtime::HOOK_ALL]);

Co::run(function()
{
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, "https://openswoole.com");
    curl_setopt($ch, CURLOPT_HEADER, false);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);

    $result = curl_exec($ch);

    curl_close($ch);
    var_dump($result);
});

CURLOPT_PROTOCOLS_STR and CURLOPT_REDIR_PROTOCOLS_STR

Since the next release

The hooked curl_setopt() supports CURLOPT_PROTOCOLS_STR and CURLOPT_REDIR_PROTOCOLS_STR, which need libcurl 7.85.0 or later. They take a comma separated list of protocol names, for example http,https, to limit the protocols curl may use for a request and for redirects.

When open_basedir is set, a value that contains file or all (in any case) is refused: curl_setopt() reports the warning The FILE protocol cannot be activated when an open_basedir is set and returns false.

<?php

Co::set(['hook_flags' => OpenSwoole\Runtime::HOOK_ALL]);

Co::run(function()
{
    $ch = curl_init('https://openswoole.com');
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
    curl_setopt($ch, CURLOPT_PROTOCOLS_STR, 'https');
    curl_setopt($ch, CURLOPT_REDIR_PROTOCOLS_STR, 'https');

    var_dump(curl_exec($ch));
});

Callbacks

Since v26.11.0, the native curl hook supports two more callbacks:

  • CURLOPT_PREREQFUNCTION on PHP 8.4 and later. Guzzle 7.12 and later use it
  • CURLOPT_SEEKFUNCTION on PHP 8.6. libcurl calls it to rewind an upload, for example when it resends a request body after a redirect or an authentication challenge
<?php

Co::set(['hook_flags' => OpenSwoole\Runtime::HOOK_ALL]);

Co::run(function()
{
    $body = str_repeat('x', 4096);
    $pos = 0;

    $ch = curl_init('https://example.com/upload');
    curl_setopt_array($ch, [
        CURLOPT_UPLOAD => true,
        CURLOPT_INFILESIZE => strlen($body),
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_READFUNCTION => function ($ch, $fp, $length) use (&$pos, $body) {
            $chunk = substr($body, $pos, $length);
            $pos += strlen($chunk);
            return $chunk;
        },
        CURLOPT_SEEKFUNCTION => function ($ch, $offset, $origin) use (&$pos) {
            $pos = $offset;
            return CURL_SEEKFUNC_OK;
        },
    ]);
    curl_exec($ch);
});
Last updated on November 20, 2026