forrest79/phpfpm-request

Run php-fpm requests from command line.

v0.8.1 2024-01-26 21:50 UTC

This package is auto-updated.

Last update: 2024-04-26 22:18:37 UTC


README

Latest Stable Version Monthly Downloads License Build

Simply utility to make php-fpm requests right from command line with no needs to set up your web server for these requests.

Installation

The recommended way to install Forrest79/PhpFpmRequest is through Composer:

composer require forrest79/phpfpm-request

This also needs cgi-fcgi installed on your system. On Debian (Ubuntu...) like linux, you can do this:

sudo apt install libfcgi0ldbl

You can you this to clear some caches from cli that need to be called via HTTP request (opcache, apcu, ...) or to warm up your cache after a new version is deployed and before web server is started to point to new source code.

How to use it

We just need to know, where is php-fpm listening. It's config directive listen and it could be socket or TCP\IP. In nginx it's directive fastcgi_pass. If you don't know that, or you're planning to run this on different systems, you can try to autodetect this:

$requester = Forrest79\PhpFpmRequest\Requester::autodetect();

Or if you know where php-fpm is listening, you can use this value:

$requester = Forrest79\PhpFpmRequest\Requester::create('/var/run/php/php7.4-fpm.sock');

Now just simple set PHP file to process with php-fpm:

$requester->setPhpFile('/var/www/index.php');

And send the request:

$response = $requester->send();

Now we have Response object, that can return array of HTTP headers and text body.

echo $reponse->getBody() . PHP_EOL;

foreach ($response->getHeaders() as $header) {
    echo $header . PHP_EOL;
}

If you need to pass more options to php-fpm, just use setOption(string $name, string $value) method. Only REQUEST_METHOD is set automatically to GET and SCRIPT_FILENAME is pass. But you can add anything you want:

$requester
    ->setOption('QUERY_STRING', '?param=1')
    ->setOption('SERVER_NAME', 'my-server.com')
    ->setOption('REQUEST_URI', '/show-detail/');

If you need better API for this, extends Requester with your own class and create better public API and in every method just call parent::setOption('...', '...').

Cli and php-fpm in one file

You can have cli and php-fpm source code in one file:

if (PHP_SAPI === 'cli') {
    echo Forrest79\PhpFpmRequest\Requester::autodetect()
        ->setPhpFile(__FILE__)
        ->send()
        ->getBody() . PHP_EOL;
} else {
    echo 'This code is processed with php-fpm. You can warm up your cache here, clean cache, etc.';
}