Programming - - By Louis Simoneau

PHP with nginx is about to Become a Lot Easier

PHP version 5.4 will most likely include the PHP-FPM patch right in the core, which is great news for those of us who like to run PHP under the nginx web server. You may be asking, “What is PHP-FPM, and why should I care?”

PHP-FPM is a patch for PHP core that handles the starting, stopping, and restarting of FastCGI processes as needed. This is important because nginx can only interface with PHP via FastCGI, unlike Apache, which loads the whole PHP environment right into itself. In addition to the performance benefits of nginx over Apache, running PHP via FastCGI rather than as an Apache module has its own benefits:

  • Lower memory usage (since extra nginx workers come without the whole weight of the PHP environment)
  • Easier permissions management (PHP can run as a different user than your server process)
  • If PHP crashes, nginx can keep going

The downside is that, compared to mod_php, the nginx, PHP, and FastCGI stack takes significantly more work to set up. In the past, the way to make this setup work was to co-opt the spawn-fcgi script from the LightTPD project, and use that to start the FastCGI process. However, there are problems with that setup: it’s fragile (if a process stops it might not be restarted correctly) and it’s a pain to set up. After installing and configuring nginx, you need to download LightTPD, grab the script in question and configure it to start automatically, then configure everything to play nicely together. If you’re used to the out-of-the-box experience of mod_php, this might convince you to just upgrade your server instead of switching to the leaner, meaner nginx.

Enter PHP-FPM. This patch bakes FastCGI process management right into PHP. So if you compile PHP with the FPM patch in place and the --enable-fpm configuration option, PHP will take care of starting and stopping processes as nginx requests them, with no additional configuration required. Of course, manually patching and compiling the PHP source is still more work than us lazy web developers would like to do, which is why it’s great news that, as of PHP 5.4, FPM will be folded into the core of the PHP project.

This means that you’ll be able to download PHP, compile it with the --enable-fpm switch, and be off to the races running it with nginx in the same amount of time and effort it would take to set up with Apache.

So if you’ve tried running PHP with nginx in the past and given up after jumping through the seventh hoop, I’d suggest you give PHP-FPM a try. At the moment there’s still a bit of hassle involved, but it’s improving all the time. In the meantime, you get to be the cool kid on the block with the sweet new toy!

Sponsors