Skip to Content

Connect directly to PHP-FPM

Posted on 2 mins read

You may have run into a situation where Nginx or Apache is suddenly returning you the dreaded 502 - Bad Gateway. One of the first things you should try is finding out where exactly the problem is coming from.

The reason for this failure could be a misconfiguration in Nginx or Apache, or it could a PHP-FPM issue. You can bypass your web server by connecting to PHP-FPM from the command line. This will tell you right away if PHP-FPM is still functioning or not.

To do this we need the cgi-fcgi tool. On Ubuntu, you can install with the following command:

apt-get install libfcgi0ldbl

Putting it to use is very straightforward. In this example we assume PHP-FPM is listening on the socket /var/run/php-fpm.sock1 for incoming connections.

Let’s create a simple test script at /tmp/info.php with the following contents:

if (substr(php_sapi_name(), 0, 9) == 'fpm-fcgi') {
echo "You are using FastCGI PHP" . PHP_EOL;
} else {
echo "You are not using FastCGI PHP" . PHP_EOL;

Then we create environment variables to pass on as FastCGI parameters. These are the least parameters required to tell PHP-FPM how to handle the request:

export SCRIPT_FILENAME=/tmp/info.php

Now connect to PHP-FPM to see the result:

cgi-fcgi -bind -connect /var/run/php-fpm.sock

If PHP-FPM is working as expected, the response will look like this:

Content-type: text/html; charset=UTF-8

You are using FastCGI PHP

If you now want to test your actual website, you can point the SCRIPT_FILENAME environment variable to your index.php file. Example:

export SCRIPT_FILENAME=/var/www/

Happy debugging!

  1. If you are unsure what port or socket PHP-FPM is listening to, you can check the value of the listen directive in your PHP-FPM pool configuration. [return]