PHP CURL with Coroutines in Open Swoole

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

Open Swoole CURL

PHP CURL can now be used within a OpenSwoole Coroutine, you can run multiple CURL requests concurrently within a single process within multiple coroutines.

As of OpenSwoole v4.6.5 there is now full support for native PHP CURL, all functions are supported, so it is now recommended to only use the native CURL hook OpenSwoole\Runtime::HOOK_NATIVE_CURL instead of the old OpenSwoole\Runtime::HOOK_CURL.

To enable coroutine support for PHP CURL, you have to enable the Coroutine Hook for CURL:

<?php
OpenSwoole\Runtime::enableCoroutine(OpenSwoole\Runtime::HOOK_NATIVE_CURL);

You must enable the coroutine hook for PHP CURL otherwise you will be blocking requests.

Example:

<?php

// enable coroutine support for native PHP CURL
OpenSwoole\Runtime::enableCoroutine(OpenSwoole\Runtime::HOOK_NATIVE_CURL);

co::run(function() {

    $ch = curl_init();

    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'GET');
    curl_setopt($ch, CURLOPT_HEADER, 0);
    curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
    curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 3);
    curl_setopt($ch, CURLOPT_TIMEOUT, 10);

    $headers = array();
    $headers[] = 'User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_13_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/80.0.3987.163 Safari/537.36';

    curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);

    $output = curl_exec($ch);
    if ($output === FALSE) {

        echo "CURL Error:". curl_error($ch). " ". $url. "\n";
        return $resp;

    }

    curl_close($ch);
});

Check PHP Coroutine about how to execute multiple coroutines concurrently.

Coroutine CURL Benefits

Before OpenSwoole v4.6.5, curl_multi is not supported within a coroutine context. Starting from v4.6.5, native PHP CURL is fully supported within a coroutine context.

You can execute multiple CURL clients concurrently with fibers within one process.

This is a major improvement, libraries such as the Guzzle HTTP client are fully compatible with OpenSwoole coroutines. You can use Guzzle with OpenSwoole coroutines without any change. All the downstream libraries such as AWS SDK for PHP and the Laravel HTTP Client which are reliant on Guzzle are also compliant with OpenSwoole coroutines.

This benefit is huge as it means you are able to gain performance boosts without having to rewrite any code, just setup OpenSwoole Coroutines.

Last updated on September 20, 2022