PHP CURL with Coroutines in Open Swoole

4.x is outdated, please check the latest version 22.x


Latest version: pecl install openswoole-22.1.2

Open Swoole CURL

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

As of Swoole 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 SWOOLE_HOOK_NATIVE_CURL instead of the old SWOOLE_HOOK_CURL.

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

<?php
Swoole\Runtime::enableCoroutine(SWOOLE_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
Swoole\Runtime::enableCoroutine(SWOOLE_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 Swoole 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 Swoole coroutines. You can use Guzzle with Swoole 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 Swoole coroutines.

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

Last updated on August 31, 2022