PHP Handlers: Why They Matter and How to Choose the Best One
PHP Handlers: Why They Matter and How to Choose the Best One
In obsessing over the best frameworks and coding practices for their PHP applications, developers often fail to look beyond their code for optimization and boosting performance. They often fail to realize the crucial role of the server setup, the PHP handlers, and the system environment in your application failing or succeeding out there.
Apache server and web hosting manager (WHM) configurations can seem obscure at first, and it’s challenging to keep track of every config option. However, as you set out to explore the internal mechanics of your application, one of the vital aspects of the pipeline is the role of the PHP handler in the processing of your PHP scripts.
This post will explore what PHP handlers are, why they are essential, and how you could choose one suited for your application. We’ll take a look at six commonly used handlers and learn more about how they operate and what they have to offer.
Here’s an outline of the post along with the list of the PHP handlers that we will cover in this post –
What are PHP Handlers?
Have you ever wondered how your raw PHP scripts are translated into a fully functional website and served to clients by your server?
When a client makes an HTTP request to your PHP application, the server takes the request and creates a new process, and forwards it to the PHP run-time on it. The run-time is responsible for taking the request and then parsing, compiling, and executing the corresponding PHP scripts before the server sends the generated response. As represented in the diagram above, this communication with the run-time is enabled by a handler.
Your Apache server needs to internally interpret your PHP code, execute it, and serve it to the client. To achieve this and function effectively, it needs an interface to load PHP libraries (e.g., version 5.6) onto the server for interpreting your code and generating your website with all its functionalities. This interface between your server and PHP’s runtime is called a PHP handler.
Handlers load the PHP libraries for your server and, in a way, inform it about how to deal with your PHP scripts. Without a handler, your PHP file is served to the client as just another downloadable file because your server has no idea of working with it.
These handlers differ in how they load and deliver these libraries by different mechanisms and implementations. Some of the most popular handlers are – CGI (Common Gateway Interface), FCGI (Fast CGI), DSO (Dynamic Shared Object), SuPHP (Single User PHP), etc. We’ll dive deep into these in a while.
Why Do PHP Handlers Matter?
As discussed in the introduction, many developers are less likely to look beyond their code when optimizing their applications. However, server environments and configurations are just as important (if not more) for serving your websites right (pun not intended).
PHP handlers determine how your server internally parses your code and utilizes the system resources to compile it and serve it on the internet. This handler middleware between your server and the PHP runtime can significantly impact performance. The more suited your handler is to your and your organization’s requirements, the more juice you can extract from your applications.
On the other hand, if not carefully considered, these handlers can also prove to be an ugly bottleneck that you likely failed to account for when identifying performance issues in your application. Therefore, it is crucial to have at least a broad understanding of what handlers are and be aware of those that your setups use.
Which PHP Handler are you Currently Using?
To know which handler your system is currently running, you can use your code’s phpinfo() function to display configuration settings and environment variables.
<?php phpinfo(); # output PHP environment settings ?>
Fire up your server and open this file on your browser. Here’s what the output would look like –
Look out for the “Server API” field here. The system uses the DSO (mod_php) handler (shown as ‘Apache 2.0 Handler’ in the image above). We’ll dive deeper into this handler later.
Now that you know what PHP handler you’ve been running, let’s look at some of the most common handlers out there, understand how they compare to yours, and get a sense of what might suit your requirements better.
How to Choose the Right PHP Handler
Each handler has its own way of parsing, compiling, and serving PHP code with its own set of pros and cons. Based on your and your organization’s requirements, your PHP handler preferences may vary. These handlers allow you to optimize for whatever matters the most for your applications instead of going with whatever has been set up by default.
Some individuals prefer speed and performance, while others care more about scalability, stability, security, or limited resource budgets. For instance, do you need caching support? Do you need to run multiple applications on your server? Does your application cater to high volumes of traffic? Are you short on CPU and RAM resources?
Let’s look at six of Apache’s most popular PHP handlers out there. We’ll discuss them in the light of the above criteria and shed some light on their pros and cons.
Note: All of these likely work with your web hosting manager, but a Google search always helps.
CGI is short-form for Common Gateway Interface and is one of the slowest and most outdated PHP handlers. The CGI (interface) essentially specifies a way for servers to deal with external content-generating scripts (also known as CGI scripts), regardless of their programming language. When it comes to PHP scripts, Apache’s mod_cgi or mod_cgid modules can help in enabling this interaction.
The CGI handler can run PHP scripts as the domain user (with the hosting account) or the file owner with the suEXEC module instead of the default “nobody” Apache user.
It operates in a non-persistent manner, i.e., for each request, instead of running the PHP code within Apache, it creates and runs a new CGI process outside the server. Because of this, even execution of possibly malicious code also happens outside Apache’s scope, making it somewhat more secure than some of the other handlers. However, overall, the CGI handler is not so secure (on its own) due to non-restrictive permissions.
Additionally, this one process-per-request model leads to low memory consumption but high CPU usage and response times. It’s one of the slowest handlers and replaced by its successor, FCGI.
CGI is common in shared hosting environments, legacy applications that haven’t cared to upgrade, and a fallback in settings when other handlers aren’t available. Even though it is highly configurable, its lack of speed and security make it unfavorable for modern applications.
- Allows running scripts as hosting account owner.
- Highly configurable through the .user.ini files.
- Inefficient, poor performance, high CPU usage; the slowest handler out there
- Lack of security due to non-restrictive permissions.
- It does not support PHP Opcode caching.
- Consequently, it is at a disadvantage for applications that receive high traffic.
- It doesn’t support .htaccess files for configuring PHP applications.
DSO stands for Dynamic Shared Object and (in stark contrast to the above) is known to be one of the fastest PHP handlers out there. Instead of creating a new process per request, Apache can parse and interpret the PHP scripts by loading PHP into an Apache child process. Moreover, mod_php (PHP as a module) utilizes opcode caching and saves precompiled bytecodes in memory, avoiding loading and parsing upon each request. As a result, this handler has less overhead, faster execution, and significantly lower response times.
This speed and performance, however, comes at a cost. By default, with DSO, your PHP scripts will be owned and executed by the Apache user (“nobody”). There are some problems associated with this --
- Security implications: Malicious scripts can access and attack files outside the site's directory.
- Loss of visibility: Inability to identify resource usage and script execution by users.
- Difficulty in updating Content Management Systems (CMS)
- Restricts the domain owner to modify, remove, or backup files created by PHP scripts because they are owned by “nobody”.
However, the good news is that one can avoid this issue by using the mod_ruid2 module to compile Apache. This allows the files and scripts to be owned and executed by the Linux domain user, making it easier to track ownership of running processes. Therefore, make sure to use DSO with the mod_ruid2 module enabled.
One other thing worth mentioning is that DSO operates only in a non-threaded mode. This means it can not benefit from Apache’s multi-processing modules (MPMs). This can be a deal-breaker for many applications, and therefore is a compromise worth considering before making a call.
Note: The DSO handler shows as ‘Apache 2.0 Handler’ in the phpinfo() output log.
- It offers support for opcode caching.
- Speedy: little overhead; faster response time.
- Allows you to use php directives (e.g. php_value, php_admin_value) through .htaccess files.
- It requires low CPU and memory consumption.
- Default execution by the Apache “nobody” user is insecure and intransparent.
- It can work only with a single PHP version on cPanel servers.
- It works with APache only in the non-threaded mode
- Does not support PHP 8 on cPanel and other web hosting managers.
SuPHP stands for Single User PHP. If DSO’s superpower was its speed, SuPHP’s is its security.
With SuPHP, all scripts run as the domain owner user. This ensures that PHP scripts and files created and collected belong to and are executable or modifiable only by that user. To provide additional security, SuPHP also runs some further security checks before executing a PHP script.
This restricted permission setup clarifies script execution and system resource usage for identifying anomalous or resource-intensive behavior. This also provides a clear distinction between different user setups and makes it favorable for running multiple applications (and CMSes) on one server instance.
However, the downside of SuPHP is its CGI-like model of spawning a separate process for each request. For applications catering in high-traffic settings, excessive process spawning in a short amount of time can be very inefficient, push the servers to their limits, and severely affect performance. However, the saving grace could come upon integrating Apache’s multi-processing modules MPMs to improve process management and resource utilization.
Nevertheless, SuPHP doesn’t support opcode caching, was last updated in 2013, and is therefore quite outdated and no longer commonly used.
- It runs scripts as a Linux user (domain owner) instead of the default Apache user.
- It prevents insecure access to user files.
- It performs additional extensive security checks before each PHP script execution.
- It is favorable for CMSes -- no need to worry about modifying user ownership and permissions.
- No persistent-state -- requires the creation of a new process for each request.
- High CPU overhead.
- Apache directives can’t be used (php.ini files used instead).
- It has not been updated since 2013.
- It doesn’t utilize caching extensions.
FCGI stands for Fast CGI and aims to make up for the limitations of its predecessor.
It gets its speed from its in-memory caching -- by storing pre-compiled PHP scripts in the shared memory and serving them instead of loading and parsing them each time.
This better utilizes the available system memory and reduces the CPU overhead by not creating a new process for each request.
As expected, however, this caching can take a toll on your system’s memory resources. But because it reduces CPU load and speeds up data retrieval, it can overall be quite helpful once you’ve figured out the right balance for your system specifications.
Additionally, unlike the DSO handler, this speed doesn’t come at the cost of security. With FCGI (thanks to SuEXEC), your scripts are executed as the domain user, providing you with all the security benefits previously discussed. This makes FCGI as secure as the SuPHP handler we discussed before but faster.
Apart from some (one-time) difficulty in getting the configurations right, FCGI’s speed and security make it an excellent option for building fast and scalable modern PHP applications.
- Can benefit from PHP caching support through persistent processes.
- Offers faster data-retrieval and low CPU usage -- overall low response time
- Secure because of executing PHP scripts as the domain owner (and not Apache user).
- Higher RAM requirements.
- Configuration directives through .htaccess are not supported.
LSAPI is perhaps the best handler on this list on many counts.
LSAPI stands for LiteSpeed’s PHP Server API, and mod_lsapi is the Apache handler based on the built-in PHP handler of the LiteSpeed Technologies API. Initially available only for CloudLinux and LiteSpeed users, it is now available to all other cPanel & WHM servers.
It is one of the relatively new kids on the Apache block but has proven more performant than others. Despite requiring less CPU and memory resources, it offers significant improvements in speed and performance for PHP websites. What makes it an even better choice is that it is good to go right out of the box without any configuration required. This is especially useful for beginners who don’t want to dive into obscure configuration options and files.
However, mod_lsapi does not offer the full capabilities of LSAPI. For example, CRIU (Checkpoint Restore In Userspace) and connection pooling are disabled in mod_lsapi; they require you to have CloudLinux with mod_lsapi PRO.
- Provides support for caching.
- It is the most performant handler with a low memory footprint.
- No configuration is required.
- It can work with multiple PHP versions in a single setup.
- It supports PHP configuration directives through .htaccess files.
- Secure because scripts execute as the domain owner.
- It does not make available all LSAPI capabilities.
PHP-FPM is the short form for PHP Fast CGI Process Manager and is an alternate implementation of the FCGI handler we discussed above for high-traffic sites.
It adds process management, emergency restart, IP address restriction, accelerated upload support, dynamic/static child spawning, and many more capabilities to FastCGI and integrates with any FCGI compatible server. Essentially, it maintains a pool of connection workers for responding to incoming requests and is known to be faster than other CGI methods like SuPHP, CGI, etc., for multi-user setups. However, this handler works best on systems with decent memory resources -- a commonly known threshold is 2GB of RAM or 30MB per domain.
- It supports opcode cache sharing among all workers.
- Persistent process handling.
- It is easier to scale -- more concurrency and throughput.
- Ships with PHP 5.3.3 onwards.
- In-depth configuration can be difficult for inexperienced individuals.
- System resource requirements can be non-trivial.
How to Change Your PHP Handler
To get information about your current handler and a list of the ones available on your cPanel server setup, you can use the following rebuild_phpconf commands on the system’s command prompt (as the root user) --
To output current PHP handler information (for all PHP versions) --
DEFAULT PHP: ea-php72 ea-php54 SAPI: cgi ea-php71 SAPI: none ea-php72 SAPI: cgi ea-php73 SAPI: cgi
To get information about available PHP handlers on your system --
Available handlers: suphp dso fcgi cgi none
Once you’ve decided which handler would be most appropriate for your application, you use the following command to switch handlers.
To change a PHP handler on an (EasyApache) server --
For example, for a PHP setup with multiple PHP versions, you can switch the handler for PHP version 7.3 to fcgi, using the following command --
This post was perhaps one of your first steps towards going beyond your PHP code and understanding your server environment, the hosting manager, and the vital role each plays in optimizing your application’s performance.
If you feel you’re missing out on performance or security, then search for one that would better suit your requirements and go for it. And while on the topic of performance and optimization, make sure to check out Scout’s APM tool for real-time performance insights and alerts about bottlenecks, memory bloat, leaks, slow database queries, and much more. Get started with a 14-day free trial (no credit card needed)! Also, check out our blog for more software programming and web development content.