Swoole PHP Coroutine FastCGI Client

Version: Swoole: 4.5.0+

Swoole Coroutine FastCGI Client can be used to communicate with FastCGI servers like PHP-FPM.

You can also use FastCGI Proxy to proxy HTTP request to your FastCGI server.

Methods

<?php
Swoole\Coroutine\FastCGI\Client->__construct(string $host, int $port = 0)

Create a new FastCGI client with the target host and port.

<?php
Swoole\Coroutine\FastCGI\Client::call(string $url, string $path, $data = '', float $timeout = -1): string```

Execute FastCGI remote call.

/tmp/greeter.php running on PHP-FPM server
<?php
echo 'Hello ' . ($_POST['who'] ?? 'World');
Call the PHP-FPM server with FastCGI client:
<?php
echo Swoole\Coroutine\FastCGI\Client::call(
        '127.0.0.1:9000', // PHP-FPM address, can also be unix://path/to/fpm.sock
        '/tmp/greeter.php', // the PHP script
        ['who' => 'Swoole'] // POST Messages
);
<?php
Swoole\Coroutine\FastCGI\Client->execute(Request $request, float $timeout = -1): Response

Execute FastCGI remote call.

PSR style example
<?php
try {
    $client = new Swoole\Coroutine\FastCGI\Client('127.0.0.1', 9000);
    $request = (new Swoole\FastCGI\HttpRequest())
        ->withScriptFilename(__DIR__ . '/greeter.php')
        ->withMethod('POST')
        ->withBody(['who' => 'Swoole']);
    $response = $client->execute($request);
    $body = $response->getBody();
    echo "Result: {$body}\n";
} catch (\Swoole\Coroutine\FastCGI\Client\Exception $exception) {
    echo "Error: {$exception->getMessage()}\n";
}
Another example with more options:
<?php
try {
    $client = new \Swoole\Coroutine\FastCGI\Client('127.0.0.1', 9000);
    $request = (new \Swoole\FastCGI\HttpRequest())
        ->withDocumentRoot(__DIR__)
        ->withScriptFilename(__DIR__ . '/var.php')
        ->withScriptName('var.php')
        ->withMethod('POST')
        ->withUri('/var?foo=bar&bar=char')
        ->withHeader('X-Foo', 'bar')
        ->withHeader('X-Bar', 'char')
        ->withBody(['foo' => 'bar', 'bar' => 'char']);
    $response = $client->execute($request);
    echo "Result: \n{$response->getBody()}";
} catch (\Swoole\Coroutine\FastCGI\Client\Exception $exception) {
    echo "Error: {$exception->getMessage()}\n";
}