Installation:
composer require mrizwan/laravel-fcgi-client
Publish the config file (if needed):
php artisan vendor:publish --provider="Mrizwan\FastCgiClient\FastCgiClientServiceProvider"
Basic Usage:
use Mrizwan\FastCgiClient\Facades\FastCgi;
$response = FastCgi::send('php://input', [
'SCRIPT_FILENAME' => '/path/to/script.php',
'REQUEST_METHOD' => 'POST',
'CONTENT_TYPE' => 'application/x-www-form-urlencoded',
]);
First Use Case: Call a PHP script on a remote PHP-FPM server to validate or process data before committing to a database.
Request/Response Handling:
// Send a request with POST data
$response = FastCgi::send('php://input', [
'SCRIPT_FILENAME' => '/var/www/app/process.php',
'REQUEST_METHOD' => 'POST',
'CONTENT_LENGTH' => strlen($data),
'CONTENT_TYPE' => 'application/json',
], json_encode(['key' => 'value']));
// Parse response
$output = $response->getOutput();
$status = $response->getStatus();
Environment-Based Configuration:
Use the config/fastcgi.php to define multiple servers (e.g., local, staging, production):
'servers' => [
'local' => [
'host' => '127.0.0.1',
'port' => 9000,
],
'production' => [
'host' => env('FCGI_HOST'),
'port' => env('FCGI_PORT'),
],
],
Then dynamically switch:
config(['fastcgi.server' => 'production']);
Retry Logic for Unstable Connections:
use Illuminate\Support\Facades\Retry;
$response = Retry::times(3, function () {
return FastCgi::send('php://input', $params);
});
Integration with Laravel Jobs:
use Mrizwan\FastCgiClient\Facades\FastCgi;
use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
class ProcessDataJob implements ShouldQueue
{
use Queueable;
public function handle()
{
$response = FastCgi::send('php://input', [
'SCRIPT_FILENAME' => '/path/to/process.php',
], $this->data);
}
}
Streaming Large Responses:
$response = FastCgi::send('php://input', $params);
while (!$response->isEnd()) {
$chunk = $response->read();
// Process chunk (e.g., log, store, or stream to client)
}
Laravel HTTP Client Proxy: Extend Laravel's HTTP client to support FastCGI:
$client = new \Illuminate\Http\Client\PendingRequest;
$client->macro('fastCgi', function ($script, $params, $body = null) {
return FastCgi::send('php://input', $params, $body);
});
Middleware for Authentication: Add a middleware to inject auth headers or tokens into FastCGI requests:
FastCgi::extend(function ($client) {
$client->before(function ($request) {
$request->setHeader('X-AUTH-TOKEN', auth()->token());
});
});
Logging: Use Laravel's logging to track FastCGI requests:
FastCgi::extend(function ($client) {
$client->after(function ($response) {
\Log::info('FastCGI Response', [
'status' => $response->getStatus(),
'output' => $response->getOutput(),
]);
});
});
Connection Timeouts:
setTimeout():
FastCgi::setTimeout(5); // 5 seconds
strace or tcpdump if connections silently fail.Environment Mismatches:
pdo_mysql) will cause silent failures.php -m on the remote server to verify extensions.Memory Limits:
memory_limit. If your script processes large data, increase it in php.ini or via ini_set() in the script.SCRIPT_FILENAME Validation:
.. or absolute paths outside its document root. Always use relative paths or validate them:
$script = str_replace(['/', '\\'], '', $_SERVER['SCRIPT_FILENAME']);
Case Sensitivity:
SCRIPT_FILENAME. Ensure paths match exactly.Persistent Connections:
setPersistent(false) if you encounter issues with stale connections.Enable Verbose Output:
FastCgi::enableDebug();
This logs raw FastCGI requests/responses to storage/logs/fastcgi.log.
Check Remote Server Logs:
Look for errors in /var/log/php-fpm.log or the equivalent on the remote server.
Test with curl:
Manually test the FastCGI endpoint using curl to isolate whether the issue is with the package or the remote server:
echo -n 'data=test' | curl --unix-socket /var/run/php-fpm.sock -X POST \
http://localhost/path/to/script.php
Socket vs. TCP:
unix:/var/run/php-fpm.sock) for local communication (faster, no port conflicts).tcp://127.0.0.1:9000) for remote servers.Default Parameters:
The package auto-sets common headers like SERVER_SOFTWARE, SERVER_PROTOCOL, and GATEWAY_INTERFACE. Override them if needed:
FastCgi::setDefaultParams([
'SERVER_SOFTWARE' => 'Laravel/FCGI',
]);
Environment Variables: The package respects Laravel's environment variables for host/port:
'host' => env('FCGI_HOST', '127.0.0.1'),
'port' => env('FCGI_PORT', 9000),
Custom Response Handling:
Extend the Mrizwan\FastCgiClient\Response class to add custom methods:
FastCgi::extend(function ($client) {
$client->after(function ($response) {
$response->setCustomMethod('isJson', function () {
return json_decode($this->getOutput()) !== null;
});
});
});
Plugin System: Use Laravel's service container to bind custom FastCGI clients:
$this->app->bind('custom.fcgi', function () {
return FastCgi::createClient([
'host' => 'custom-server',
'port' => 9001,
]);
});
Event Listeners: Dispatch events before/after requests:
FastCgi::before(function ($request) {
event(new FastCgiRequestEvent($request));
});
How can I help you explore Laravel packages today?