Join 4,000+ others and never miss out on new tips, tutorials, and more.
4.x is outdated, please check the latest version 22.x
Latest version:
pecl install openswoole-22.1.2
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
.
<?php
// /tmp/var_dump.php
var_dump($_SERVER);
var_dump($_GET);
var_dump($_POST);
<?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
Co\run(function()
{
// We use a try-catch to process any errors if something goes wrong
try
{
// Create a new client based on host and port, can also use a UnixSocket
$client = new Swoole\Coroutine\FastCGI\Client('127.0.0.1', 9000);
// Builds up the request we want to send, with many options...
$request = (new Swoole\FastCGI\HttpRequest())
->withDocumentRoot(__DIR__)
->withScriptFilename(__DIR__ . '/tmp/var_dump.php')
->withScriptName('var_dump.php')
->withMethod('POST')
->withUri('/tmp/var_dump?foo=bar&bar=char')
->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.