Weave Code
Code Weaver
Helps Laravel developers discover, compare, and choose open-source packages. See popularity, security, maintainers, and scores at a glance to make better decisions.
Feedback
Share your thoughts, report bugs, or suggest improvements.
Subject
Message

Laravel Fcgi Client Laravel Package

mrizwan/laravel-fcgi-client

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation:

    composer require mrizwan/laravel-fcgi-client
    

    Publish the config file (if needed):

    php artisan vendor:publish --provider="Mrizwan\FastCgiClient\FastCgiClientServiceProvider"
    
  2. 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',
    ]);
    
  3. First Use Case: Call a PHP script on a remote PHP-FPM server to validate or process data before committing to a database.


Implementation Patterns

Common Workflows

  1. 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();
    
  2. 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']);
    
  3. Retry Logic for Unstable Connections:

    use Illuminate\Support\Facades\Retry;
    
    $response = Retry::times(3, function () {
        return FastCgi::send('php://input', $params);
    });
    
  4. 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);
        }
    }
    
  5. 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)
    }
    

Integration Tips

  • 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(),
            ]);
        });
    });
    

Gotchas and Tips

Pitfalls

  1. Connection Timeouts:

    • FastCGI connections may hang if the remote server is overloaded. Use setTimeout():
      FastCgi::setTimeout(5); // 5 seconds
      
    • Debug with strace or tcpdump if connections silently fail.
  2. Environment Mismatches:

    • Ensure the remote PHP-FPM server has the same PHP extensions as your Laravel app. Missing extensions (e.g., pdo_mysql) will cause silent failures.
    • Test with php -m on the remote server to verify extensions.
  3. Memory Limits:

    • FastCGI scripts inherit the remote server's memory_limit. If your script processes large data, increase it in php.ini or via ini_set() in the script.
  4. SCRIPT_FILENAME Validation:

    • The remote server may reject paths with .. or absolute paths outside its document root. Always use relative paths or validate them:
      $script = str_replace(['/', '\\'], '', $_SERVER['SCRIPT_FILENAME']);
      
  5. Case Sensitivity:

    • Some servers (e.g., Linux) are case-sensitive for SCRIPT_FILENAME. Ensure paths match exactly.
  6. Persistent Connections:

    • The package reuses connections by default. Disable with setPersistent(false) if you encounter issues with stale connections.

Debugging

  • 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
    

Configuration Quirks

  1. Socket vs. TCP:

    • Prefer Unix sockets (unix:/var/run/php-fpm.sock) for local communication (faster, no port conflicts).
    • Use TCP (tcp://127.0.0.1:9000) for remote servers.
  2. 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',
    ]);
    
  3. 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),
    

Extension Points

  1. 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;
            });
        });
    });
    
  2. 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,
        ]);
    });
    
  3. Event Listeners: Dispatch events before/after requests:

    FastCgi::before(function ($request) {
        event(new FastCgiRequestEvent($request));
    });
    
Weaver

How can I help you explore Laravel packages today?

Conversation history is not saved when not logged in.
Prompt
Add packages to context
No packages found.
codeflextech/permission-manager
karnoweb/livewire-datepicker
sayedenam/sayed-dashboard
milito/query-filter
apiboxsym/user-bundle
apiboxsym/health-check-bundle
jayeshmepani/jpl-moshier-ephemeris-php
elnasnato/laraliveui
labrodev/rest-sdk
sampaui/sampaui
babelqueue/php-sdk
facebook/capi-param-builder-php
babelqueue/symfony
hamzi/corewatch
minionfactory/raw-hydrator
hexters/coinpayment
rjcodes/rjcms
act-training/laravel-permissions-manager
alimarchal/laravel-chart-of-accounts
babenkoivan/elastic-scout-driver