Running the Right Version of PHP in WordPress

Today’s hair-pulling exercise brought to you by WordPress, Apache and PHP!

WordPress is a wonderful blogging/website platform…but it isn’t terribly well-documented, in part because it can run under lots of different environments, each of which does the same things differently. So oftentimes “simple” things end up being really complex because of unappreciated interactions between all the moving parts it’s based on.

If you run WordPress under Apache you may end up in a situation where you want to use different versions of PHP for different sites (WordPress’ ecosystem takes a l-o-n-g time to respond to PHP upgrades). But getting WordPress to use the desired version of PHP isn’t easy, and most of the instructions I found on the web don’t work. Or rather they do work…but they don’t end up changing which version of PHP is being used.

Here’s the basic outline of most of those “how to” guides:

  • Install desired verison of PHP (7.4, in my case) all required addons
  • Disable the version of PHP you’re currently using (8.1, in my case) in apache2 via a2dismod php8.1
  • Enable the desired version of PHP in apache2 via a2endmod php8.1
  • Change the system default via update-alternatives –config php
  • Restart the apache server

Unfortunately, that didn’t do the job in my case. WordPress’ “site health” tool still reported PHP8.1 was being used. That was true even after I rebooted the server (okay, that was a sign of growing desperation).

The problem stems from the fact that modern WordPress installations use Yet Another Service, php-fpm, to accelerate how they serve pages. Each version of PHP comes with its own corresponding version of php-fpm (e.g., my system had both php-fpm8.1 and php-fpm7.4 running on it).

Apparently, by default, if you don’t specify the version of PHP for Apache to use in a site’s configuration file it uses the most recent one.

So the solution is relatively simple…once you stumble across it. Add the following to the site’s Apache config file:

# Specify which version of PHP to run since we have several
# (added 6/17/2022 per https://www.digitalocean.com/community/tutorials/how-to-run-multiple-php-versions-on-one-server-using-apache-and-php-fpm-on-ubuntu-18-04)
<FilesMatch \.php$>
    # For Apache version 2.4.10 and above, use SetHandler to run PHP as a fastCGI process server
    SetHandler "proxy:unix:/run/php/php7.4-fpm.sock|fcgi://localhost"
</FilesMatch>

and then restart the Apache server and you’re done.

Leave a Comment

Your email address will not be published.

Categories
Archives