Swoole FastCGI Client Advanced Example

Latest version: pecl install openswoole-4.11.1

The Swoole FastCGI Client supports coroutines when executed inside a coroutine context like Co\run or within a go() call. This example shows the use of multiple available options, use of GET variables and POST data. This example also shows how to use HTTP headers and how to handle errors with a try-catch.


We have two files to consider, the first one being var_dump.php which is on the FastCGI PHP-FPM side, the actual PHP code we make a request for and the second file being the actual code which holds the Swoole FastCGI Client code, this can be executed by running php swoole_fastcgi_client.php.


// /tmp/var_dump.php

// /tmp/swoole_fastcgi_client.php

use Swoole\FastCGI\HttpRequest;
use Swoole\FastCGI\HttpResponse;
use Swoole\Coroutine\FastCGI\Client;

// The FastCGI client must run within a coroutine context
    // We use a try-catch to process any errors if something goes wrong
        // Create a new client based on host and port, can also use a UnixSocket
        $client = new Swoole\Coroutine\FastCGI\Client('', 9000);

        // Builds up the request we want to send, with many options...
        $request = (new Swoole\FastCGI\HttpRequest())
            ->withScriptFilename(__DIR__ . '/tmp/var_dump.php')
            ->withHeader('X-Foo', 'bar')
            ->withHeader('X-Bar', 'char')
            ->withBody(['foo' => 'bar', 'bar' => 'char']);

        // Returns a Swoole\FastCGI\HttpResponse
        $response = $client->execute($request);

        echo "Result: \n{$response->getBody()}";
    catch(Swoole\Coroutine\FastCGI\Client\Exception $exception)
        echo "Error Code: {$exception->getCode()}\n";
        echo "Error Message: {$exception->getMessage()}\n";

The Swoole FastCGI client will make a request using the FastCGI protocol to the PHP-FPM server, execute the given PHP file, capture the response and return it back, allowing you to interact with FPM servers from Swoole.

Last updated on March 31, 2022