PHP

From Just another day in the life of a linux sysadmin
Jump to: navigation, search

creates phpinfo page for current user

cpUser=`pwd | cut -d/ -f3`; for i in `pwd`; do touch $i/lw-phpinfo.php; chown $cpUser. $i/lw-phpinfo.php ; echo "<?php phpinfo(); ?>" > $i/lw-phpinfo.php; done


Tail that log

tail -50000 /var/log/php_maillog | awk -F"[" '{print $3}' | awk -F']' '{print $1}' | awk -F".php" '{print $1".php"}' | sort | uniq -c | sort -nr

Handlers



There are 4 major PHP handlers available on Apache. These include mod_php (AKA DSO), CGI, FastCGI, and suPHP. If you’re using another web server your options may be different (for example, nginx requires FastCGI). Each of these handle memory, CPU, and file permissions in a different way.

mod_php (DSO)
DSO (which is short for Dynamic Shared Object) or mod_php is the oldest and, some would say, the fastest PHP handler available. It essentially makes PHP a part of Apache by having the Apache server interpret the PHP code itself through use of an Apache module known as mod_php. This is the default handler typically installed when installing a web server package on your server.

On the plus side mod_php is fast, in fact very fast as it runs directly in the same process as your Apache server. Running it together with Apache also means that it has a very low CPU and memory requirement which may be beneficial in situations where computing resources are limited.

The major drawback of mod_php is that it runs as part of Apache which means that it runs as the same user that your Apache process runs as (if you’re on Ubuntu this would www-data). This means that all work on files will be done as the Apache user which therefore must have permissions to all of your files.


CGI
CGI is the fallback in most servers when mod_php is not available. Instead of running the PHP code within Apache it is now run as it’s own CGI process, that is, in a program outside of your Apache server.

By default CGI will be called by the Apache server meaning that it will run as the Apache user with all the problems of doing so that mod_php encountered. Unlike mod_php however CGI has the ability to see the PHP as another user (presumably the user that owns the files) using another Apache module known as suexec.

For performance CGI is not nearly as fast as mod_php and requires more CPU time. It is however still soft on memory usage which may be a benefit to some users.

suPHP


suPHP runs PHP outside of the Apache script as CGI. Unlike CGI however it will run the scripts as a user other than the Apache user (presumably the user that owns the files). This means that if you are using a CMS you will be able to upload files from within your web application using suPHP. In addition, because your PHP is being run as a different user any vulnerability in your site can be restricted to only the files of your website thereby providing substantial security benefits particularly on servers that run multiple websites.

The cost of the upload ability and security of suPHP is not cheap. suPHP is slow and requires quite a bit of CPU to process all the files. In addition, as it must process the file each and every time it is called, suPHP cannot use any OPCode caching such as APC or memcached resulting in even higher CPU usage by your application. If you are running on a low-end VPS or other server with an application such as WordPress this configuration can easily push you passed any CPU limits you might have whenever traffic starts to climb.


FastCGI

FastCGI is the last major PHP handler. It offers the security benefits of suPHP by executing files as the owner of the file. Unlike suPHP however it keeps open a session for the file when the processing is done resulting in significant memory use but also allowing for the use of OPCode caching such as APC or memcached. If you do have the memory for it however FastCGI is arguably the fastest handler even in comparison with mod_php (See Running Apache+FastCGI+suexec in Ubuntu without /var/www for more help in getting started with FastCGI).


PHP-FPM

PHP-FPM is the implementation of FCGI for easyapache4 . PHP-FPM is PHP's FastCGI implementation; PHP-FPM runs as a standalone FastCGI server and Apache connects to the server using Apache's module, usually mod_fcgid or mod_fastcgi



FCGI Overview

FCGI is one of many [PHP handlers] that Apache can use to interpret PHP code. The handlers are responsible for reading / interpreting PHP code then compiling it and executing the code. Selecting the best PHP handler for your server is critical to overall performance.

Once mod_fcgid is enabled, all PHP processing is done via the FastCGI protocol. mod_fcgid starts up a certain amount of persistent processes that listen for new PHP requests and process them when needed. These processes remain alive even if there are no PHP requests, so you must make sure you configure FCGID to run an appropriate amount of processes, otherwise the server might waste a lot of resources on idle PHP processes.

Generally speaking, you should keep a few (2 or 3) idle FCGID processes running to quickly respond to new requests, that way you limit idle resource usage, but still allow for FCGID to spawn more processes if traffic picks up. To determine the maximum FCGID processes you will want to determine how much Memory the average PHP process uses, then divide the available server RAM by this number.

There is no benefit in setting the max process limit too high, otherwise you will risk server instability, especially if it starts to utilize swap space due to lack of RAM. Generally 10 or 20 max FCGID processes is a good place to start.

Why FCGI instead of SuPHP?

  • Because FCGI is faster (3 - 5 times faster) than SuPHP.
  • Because FCGI has persistent processes, opcode caching is much more effective. Meaning less CPU is used to serve PHP.

Most distributions shipping in 2013 provide precompiled packages that let you run php with fcgid. If you look around you will see that in general, no one really suggests using DSO or suphp because there are better alternatives out there such as fcgi and PHP-FPM.

In a perfect world, cPanel would already have support for PHP-FPM, while it's possible to use PHP-FPM on cPanel, it's not officially built in and could potentially break lots of things down the road. Because of that we are stuck with FCGI for the time being.

FCGI is significantly faster than suPHP, and runs PHP as the user. In general you can swap out suPHP for FCGI and vice versa without having to modify file permissions or worry about sites breaking. There may be some cases where FCGI does not work with a customer's site, but a vast majority of the time FCGI should be the go to option.

A picture is worth 1000 words :D

File:LW WIKI FCGI SUPHP OPCACHE BENCHMARKS.png

FCGI Benefits

  • Huge performance boost, both in CPU and memory consumption
  • PHP runs as the user, just like suphp, assuming SuEXEC is enabled

Since FCGI processes are separate from Apache processes, we can fine tune the maximum amount of resources we want PHP to use, but still let Apache serve static content. You cannot do this with suphp unless you severly restrict Apache Max Clients, which generally is not worth messing around with.


FCGI Considerations for Shared Servers

One thing to keep in mind if you plan on using FCGI on a server that has say, 21 + cPanel accounts on it. If the server has 1GB of RAM, you might set FcgidMaxProcesses to 20 to limit memory usage and prevent too many requests from locking up the server due to too much swap usage, or overloading your CPU.

This is all fine in most cases, but what happens if 20 of the sites already has a PHP process running as their own user, and someone tries to view website #21? Nothing happens, the website will hang and try and load for a long time, waiting for one of the occupied 20 FCGI processes to die off and be reborn again so it can serve user #21. In some cases this take be a minute or more. Obviously this is not a good thing, customer #21 is going to be mad their site doesn't load.

Why does this happen? Because of the way FCGI handles processes and what to do with them once they are done handling requests. For a single website, the ideal FCGI configuration would be to create 10 processes, or however many you want, then set their life time to a large number, like 600 seconds or more. You would do this because of opcode caching, it's best to reuse cached PHP as much as possible to reduce CPU load.

For a shared server though, long running PHP processes are not ideal unless you have enough memory to give every user a single FCGI process, but if you have limited memory and 1000 cpanel accounts, that's not going to be possible since 1000 processes using 32MB each is probably more than 2GB or whatever small amount of memory your server might have.

If you have a server with limited memory and lots of cpanel accounts and you can't set FcgidMaxProcesses to a value higher than the # of users, then your only option is to significantly reduce the timeouts, lifetimes and increase scan intervals to kill off idle processes faster, and create new processes sooner.

While I can't say this would be the best configuration, I will say that it will reduce the chances of a "spinning website" or one that takes 30 seconds to load. By using 5 second intervals the worst case would be a 5 second delay, which sucks, a lot, but it's better than 30 seconds or more. For this to happen, 21 people all over the world would need visit 20 sites on your server within the same 5 seconds, then one other person would need to visit site #21 to run into the issue I described above, but it can happen.

Anyway, if this sounds like the problem you are having, try to use very low idle timeout and process lifetimes, this may reduce performance a but, but FCGI is still WAAAAY better than SuPHP.

<IfModule mod_fcgid.c>
FcgidMaxRequestLen                      1073741824
FcgidOutputBufferSize                   1073741824
FcgidMinProcessesPerClass               0
FcgidMaxRequestsPerProcess              0
FcgidInitialEnv PHP_FCGI_MAX_REQUESTS   0
FcgidInitialEnv PHP_FCGI_CHILDREN       0
FcgidMaxProcesses                       20
FcgidMaxProcessesPerClass               10
FcgidFixPathinfo                        1
FcgidIdleTimeout                        3
FcgidBusyTimeout                        300
FcgidProcessLifeTime                    300
FcgidIOTimeout                          300
FcgidIdleScanInterval                   1
FcgidErrorScanInterval                  1
FcgidZombieScanInterval                 1
</IfModule>

I ran some quick tests to try and show how the IdleScanInterval and IdleTimeout settings can effect website load time. The results below were gathered on a cPanel server. I created 15 accounts and installed WordPress on each account. I then configured cPanel to use FCGI as the PHP handler and enabled PHP 5.5's built in OPcache. I limited FcgidMaxProcesses to 10 to replicate the issue. The theory was that after I curl the first 10 test sites, the other 5 sites would take significantly longer to load because the 10 FCGI processes would remain idle until the timeouts / scans decided it was time to kill the process off.

New processes can only be created once one of the existing 10 processes dies. As you can see here the most dramatic improvement happened when I lowered IdleTimeout from 300 (Orange Column) to 30 (Yellow Column). The longest delay between a page load dropped from 1 minute to 35 seconds.

Since IdleTimeout seems to be a huge factor, I lowered it again, from 30 seconds to 3 seconds (Blue Column). As you can see the delay dropped from 35 seconds to 9 seconds. Not bad, but if my website took 9 seconds to load, or even begin to display content I would not be happy. The green column looks much better, with a delay of 3 seconds. If you want to have the green column performance, you can have it! Below this section are some configurations based on various amounts of RAM which will provide good performance and will quickly kill off idle FCGI processes so that new ones can be created.

File:FCGI max processes website loading delay hangup.png

This is not an issue that will happen very often. The script I used is requesting 15 webpages as fast as it can. For the same situation to happen in the real world, 15 people would need to request 15 sites on your server within the same 6 seconds to notice a slight delay. On servers with a lot of traffic, this might be a common thing to have happen, but I'm testing out these settings for a 1GB VPS server, which is rather small. If I had 2GB of memory I would have raised FcgidMaxProcesses to at least 20, and none of this would be an issue.

Enabling and Configuring FCGI on a cPanel Server

CloudLinux servers need to have the php5 binaries added to CageFS or the sites will not render. cat /etc/redhat-release to see if CloudLinux is what you're working with. You may need to run cagefsctl --force-update to get /usr/share/cagefs-skeleton/usr/local/cpanel/cgi-sys/php5 in place. If you're getting 500 errors, /usr/local/apache/logs/suexec_log should tell you if the binary is missing.

The first thing to check is whether or not FCGI is listed as an available PHP handler. Run this command to see what the current handler is, and what handlers are available.

/usr/local/cpanel/bin/rebuild_phpconf --current

##Example Output

Available handlers: fcgi cgi none

If you see fcgi listed, you can switch to it like so:

/usr/local/cpanel/bin/rebuild_phpconf 5 none fcgi 1

If you do not see fcgi listed then you will need to run EasyApache and select Mod FastCGI. I also recommend upgrading PHP to at least 5.5 and making sure that Apache is updated to at least version 2.4 with the EVENT MPM enabled.

/scripts/easyapache

These suggestions assume the customer is running on a relatively updated cpanel server. If they are using a very old version then some of the steps may not apply, if that is the case I highly recommend you get WHM / cPanel updated to the lastest version.

Make sure updating PHP is ok with the customer, some sites might be using older CMS, so make sure sites load after you apply these settings. If the customer must be at PHP 5.3 or 5.4 that's ok, but in general newer versions of PHP are faster and more secure.

Once EA is done you will want to run this command to make sure EVENT is in use.

httpd -V | grep MPM

The image below shows the default WHM configuration, using SuPHP as the handler. I have already ran EA, so FCGI is listed here, if it is not listed then you need to rerun EA and select Mod FastCGI. Anyway, make sure this is set to FCGI, then click "save new configuration". This usually takes less than 10 seconds to switch over. SuPHP and FCGI both use the same permissions for www/ so you should not need to update permissions before changing these two handlers.

500px


If the server is using DSO, please follow the procedure in our wiki on how to update www permissions so that the change to FCGI will not result in broken websites.


Now it's time to configure fcgi and Apache Event default settings. To do this we will place both fcgi and event directives in /usr/local/apache/conf/includes/pre_virtualhost_global.conf. We are doing this to prevent cpanel settings from messing up our configuration, as cPanel likes to replace / remove some directives if they are placed in the main httpd.conf file.

If you are using Apache 2.4 Event with FCGI then the settings below should be a great starting point. If you are using Apache 2.2 then you may get some warnings about MaxRequestWorkers not being valid, if this is the case please remove the MaxRequestWorkers directive and replace with MaxClients. If the PHP memory limit is 128MB or higher then you might want to lower the FcgidMaxProcesses value, which sets the limit on how many PHP processes can run at once. If you set FcgidMaxProcesses too high you are allowing the server to go OOM which is NOT good.

vim /usr/local/apache/conf/includes/pre_virtualhost_global.conf

##Apache Event Default Settings (overrides main httpd.conf)##
##Please do not modify these settings unless you absolutely need to##

KeepAlive               On
KeepAliveTimeout        2
MaxKeepAliveRequests    500
<IfModule event.c>
ThreadsPerChild         25
ServerLimit             16
MaxRequestWorkers       400
StartServers            6
MinSpareThreads         150
MaxSpareThreads         400
MaxRequestsPerChild     5000
</IfModule>


<IfModule mod_fcgid.c>
FcgidMaxRequestLen                      1073741824
FcgidOutputBufferSize                   1073741824
FcgidMinProcessesPerClass               0
FcgidMaxRequestsPerProcess              0
FcgidInitialEnv PHP_FCGI_MAX_REQUESTS   0
FcgidInitialEnv PHP_FCGI_CHILDREN       0
FcgidMaxProcesses                       20
FcgidMaxProcessesPerClass               10
FcgidFixPathinfo                        1
FcgidIdleTimeout                        3
FcgidBusyTimeout                        300
FcgidProcessLifeTime                    300
FcgidIOTimeout                          300
FcgidIdleScanInterval                   1
FcgidErrorScanInterval                  1
FcgidZombieScanInterval                 1
</IfModule>

FCGI Wrapper local PHP ini issues

Server API CGI/FastCGI custom php.ini setup

root@host3 [/home/USER/public_html]# vim /usr/local/cpanel/cgi-sys/php5

added this

-f ~/public_html/php.ini && exec /usr/bin/php -c ~/public_html/php.ini If you customize the contents of this wrapper script, place a copy at /var/cpanel/conf/apache/wrappers/php5 so that it will be reinstalled when Apache is updated or the PHP handler configuration is changed

root@host3 [/home/USER/public_html]# mkdir /var/cpanel/conf/apache/wrappers root@host3 [/home/USER/public_html]# cp /usr/local/cpanel/cgi-sys/php5 /var/cpanel/conf/apache/wrappers/php5

Loading the proper ini now


FCGI Configuration File Locations

/usr/local/apache/conf/php.conf includes a few fastcgi settings, this is what cPanel applies by default. You should not have to modify this file 99.99% of the time.

# This file was automatically generated by the Cpanel PHP Configuration system
# If you wish to change the way PHP is being handled by Apache on your system,
# use the /usr/local/cpanel/bin/rebuild_phpconf script or the WHM interface.
#
# Manual edits of this file will be lost when Apache is updated.


# Fastcgi configuration for PHP5
LoadModule fcgid_module modules/mod_fcgid.so
MaxRequestsPerProcess 500
AddHandler fcgid-script .php5 .php4 .php .php3 .php2 .phtml
FcgidWrapper /usr/local/cpanel/cgi-sys/php5 .php5
FcgidWrapper /usr/local/cpanel/cgi-sys/php5 .php4
FcgidWrapper /usr/local/cpanel/cgi-sys/php5 .php
FcgidWrapper /usr/local/cpanel/cgi-sys/php5 .php3
FcgidWrapper /usr/local/cpanel/cgi-sys/php5 .php2
FcgidWrapper /usr/local/cpanel/cgi-sys/php5 .phtml

/usr/local/apache/conf/includes/pre_virtualhost_global.conf This is where we set fcgi directives like the ones covered in the sections below. By default cPanel does not really apply any settings other than what is shown below.

<IfModule mod_fcgid.c>
    FcgidMaxRequestLen 1073741824
</IfModule>

mod_fcgid configuration settings

FcgidMaxRequestLen

If the size of the request body exceeds this amount, the request will fail with 500 Server Error. By default this is set to 131072 Bytes. For cPanel the default is 1073741824, which is about 1GB.

<IfModule mod_fcgid.c>
    FcgidMaxRequestLen 1073741824
</IfModule>

FcgidMaxProcessesPerClass a.k.a. Per user

The PerClass directive is a system user account based restriction. Setting this directive does not trump the FcgidMaxProcesses directive, which is a ceiling above this PerClass directive. Setting this directive depends mostly on the server hardware limits and type of server. I follow these guide-lines when considering the PerClass limit:

The Default

The default value here is 100, this is a generic default and in most circumstances will not be ideal for the server. You will need to raise or lower this value depending on the type of server:

Shared Servers

Shared servers should have a more restrictive PerClass limitation. This is a governor to prevent a single account on the server from monopolizing all the PHP processing slots the server is capable of running at one time. In order to know the exact value you should set here, you will need to profile the server over the course of a day or longer and keep track of how many PHP processes each user uses over time. In general without profiling the server this setting is a judgment call. It ranges between 10% - 50% of the servers FcgidMaxProcesses directive. Servers which are capable of higher MaxProcesses can likely set this closer to 10% of the FcgidMaxProcesses directive. While servers with lower system memory will likely need to have this closer to the FcgidMaxProcesses.

Example: A shared server which is capable of running 250 FcgidMaxProcesses but has 100 accounts would work well with the PerClass limit of 50 processes like so.

```

   FcgidMaxProcesses 250
   FcgidMaxProcessesPerClass 50  

```

This, in theory, would allow sites to explode with traffic over short bursts while retaining enough available processing slots for the rest of the accounts on the server. The caveat in this particular configuration would limit the server to 5 busy sites all receiving traffic surges at once before issues with other sites would be realized.

Dedicated Servers

Dedicated servers which are only running a single or a handful of associated sites generally do not want to restrict their processes limits beyond the FcgidMaxProcesses directive. However, if the capabilities of the dedicated server's hardware push the FcgidMaxProcesses directive above 100, then the PerClass limit will need to be raised to match the global limit so that the user account that controls the site has access to process slots beyond the 100 mark. The same example from the above looks a little different on a dedicated server:

Example: A dedicated server which is capable of running 250 FcgidMaxProcesses but has 5 accounts wants the accounts to be able to run more than the 100 default PerClass limit. In this instance we simply match the PerClass and global limits to ensure the sites have full access to all PHP processing slots:

```

   FcgidMaxProcesses 250
   FcgidMaxProcessesPerClass 250  

```

The issues with one site consuming all the processing slots is usually moot on these servers as they tend to have a single monster site with a couple of smaller sites that have very little traffic. The majority of PHP processing is needed by the main account on the dedicated server so you want it to be able to use all the resources available form the system when it needs to.


<IfModule mod_fcgid.c>
##    FcgidMaxProcessesPerClass 100 (Default)
    FcgidMaxProcessesPerClass 0 (ideal for shared environments)
</IfModule>

FcgidMaxProcesses

This sets the global / server limit for how many PHP processes can run. Unlike the FcgidMaxProcessesPerClass directive, which is a per user limit, this directive is for all users. This is basically MaxClients but for PHP.

<IfModule mod_fcgid.c>
    FcgidMaxProcesses 100
</IfModule>

FcgidMaxRequestsPerProcess

FastCGI application processes will be terminated after handling the specified number of requests. By default this is set to 0 which means there is no limit / check.

There is a known caveat that causes sites to throw what appears to be a random 500 Internal Server Error when running FCGI and the Apache, FCGI and PHP layers all do not agree on the amount of requests that should be sent to a process. One or another of each of the layers will expect another request be sent to the process, while the others expect the process to be recycled. By default this occurs every 500 requests on cPanel as the default cPanel FCGI Wrapper sets this directive to 500. The default max requests behavior of apache is 10,000 requests and the default PHP behavior is unlimited requests. The best way to avoid this caveat is to equalize all three layers so they agree on the number of requests a process should handle. My practice is to default this to the Apache default value of 10,000. However, if the PHP software being ran on the server has large memory leaking problems, this value may be too high so adjust it downward if needed. Setting this too low will cause PHP processes to be recycled too frequently during traffic spikes adding further load to an already busy system.

MaxRequestsPerChild 10000
<IfModule mod_fcgid.c>
    FcgidInitialEnv PHP_FCGI_MAX_REQUESTS 10000
    FcgidInitialEnv PHP_FCGI_CHILDREN 0
    FcgidMaxRequestsPerProcess 10000
</IfModule>
  • MaxRequestsPerChild :: This directive controls the apache layer's max request per process expectation
  • FcgidInitialEnv  :: This directive is used to set environment values
    • PHP_FCGI_MAX_REQUESTS :: This environment value controls the number of requests PHP expects a process to handle before being recycled.
    • PHP_FCGI_CHILDREN :: This environment value controls how many children PHP should manage. We want to force this to 0 so that PHP does not prematurely recycle processes.

FcgidConnectTimeout

This is the maximum period of time the module will wait while trying to connect to a FastCGI application on Windows. (This directive is not respected on Unix, where AF_UNIX defaults will apply.)

FcgidIOTimeout

This is the maximum period of time the module will wait while trying to read from or write to a FastCGI application. If you have a slow application you may want to raise this, however 40 seconds is plenty of time. IF you site / app takes 40 seconds to load then odds are no one will ever want to visit your site again. (Either that, or you have a back-end application that takes awhile to run.. large report crons immediately come to mind) This is what you are hitting if you get "mod_fcgid: read data timeout in 40 seconds" errors.

FcgidIdleTimeout

Application processes which have not handled a request for this period of time will be terminated, if the number of processses for the class exceeds FcgidMinProcessesPerClass. A value of 0 disables the check. The default value is 300 seconds.

<IfModule mod_fcgid.c>
    FcgidIdleTimeout 300
</IfModule>

FcgidMinProcessesPerClass

This directive sets the minimum number of processes that will be retained in a process class after finishing requests. By default the value is 3.

In a cpanel server, the "class" it refers to is the domain-user. Up to this number of processess will be kept alive, even if they would otherwise be closed because of the various idle or lifetime timeouts. As a result, it is strongly recommended that you set this value to 0, unless the server is dedicated to a single, or relatively few, sites (or domain users).

<IfModule mod_fcgid.c>
    FcgidMinProcessesPerClass 3
</IfModule>

Generally you do not want to raise this value past 3 unless the website is getting tons of traffic and you start to notice time out issues with the website. On a shared server with many websites and cPanel users you will want to start with 1 Process Per Class. If there are 100 cPanel Users on the server, that means there could be up to 100 PHP processes running at any given time.

FcgidProcessLifeTime

Idle application processes which have existed for greater than this time will be terminated, if the number of processses for the class exceeds FcgidMinProcessesPerClass. A value of 0 disables the check. By Default this is set to 3600, if you want to save RAM you can set this to something like 30 to kill off unused processes

<IfModule mod_fcgid.c>
    FcgidProcessLifeTime 60
</IfModule>

FcgidIdleScanInterval

This is the interval at which the module will search for processes which have exceeded FcgidIdleTimeout or FcgidProcessLifeTime. The default is 120 seconds, you can lower this if you want shorter living processes.

<IfModule mod_fcgid.c>
    FcgidIdleScanInterval 60
</IfModule>

FcgidOutputBufferSize

A common issue that occurs when FCGI and PHP do not agree with each other on the size of their output buffers. By default, the FCGI output buffer is very small: 64 bytes. By default the PHP output_buffering is off. However, if anything changes the php output_handler or an output_buffering function is used, (typically compression software) PHP's default behavior is to automatically switch output_buffering to On without a size limit. When this occurs and the buffered data is larger than the FCGI buffer (which most everything is larger than 64 bytes) PHP will exit unexpectedly terminating additional script processing. This will also cause FCGI to spawn a new PHP process to replace the recently terminated one. You can see evidence of this occurring in the Apache error logs like this:

[Thu May 21 18:16:28.473965 2015] [fcgid:warn] [pid 503235:tid 140590471661312] (104)Connection reset by peer: [client 10.30.4.155:49167] mod_fcgid: error reading data from FastCGI server
[Thu May 21 18:16:28.474001 2015] [fcgid:warn] [pid 503235:tid 140590471661312] (104)Connection reset by peer: [client 10.30.4.155:49167] mod_fcgid: ap_pass_brigade failed in handle_request_ipc function

Should the a site use significant output_buffering, the server can easily become over-loaded filling up with PHP processes as they are constantly terminated and started. Driving the load levels of the system up.

This is remedied by getting FCGI to accept a large enough buffer for the software that is running. The buffer size should be at-least equal to or larger than the defined PHP memory_limit directive. Below is a sample of setting the buffer to 1G which should cover most scenarios:

<IfModule mod_fcgid.c>
    FcgidOutputBufferSize 1073741824
</IfModule>

You will of course need to stop/start apache for this to take affect, but it should resolve the majority of errors this situation produces.

FcgidFixPathInfo

This directive is commonly mis-configured. This is due to the a change in expected default behavior between PHP versions. Apache describes this directive as follows:

This directive enables special SCRIPT_NAME processing which allows PHP to provide additional path information. The setting of FcgidFixPathinfo should mirror the cgi.fix_pathinfo setting in php.ini.

The default value for FcgidFixPathInfo is 0 which matches that of the default value of cgi.fix_pathinfo in some older versions of PHP. Since PHP 5.4 the default value of cgi.fix_pathinfo is now 1 instead of 0. So out of the box this directive comes misconfigured on modern systems. Typically, you will just need to set this directive to 1 to correct the problem. However, since cgi.fix_pathinfo can be changed as with all php directives. It's good practice to verify in the system php.ini (and any custom php.ini files) that the cgi.fix_pathinfo directive is unset (which is equal to 1). Setting the directive to one is as simple as:

<IfModule mod_fcgid.c>
    FcgidFixPathInfo 1
</IfModule>

However, if the php.ini defines cgi.fix_pathinfo=0 then you can either change the 1 from above to 0 or remove the directive all together.


FcgidCmdOptions (app/script specific config)

New Method

Since mod_fcgid 2.3.3 it is now possible to set certain directives directly in an individual apache vhost. The directives that are supported by this are:

FcgidBusyTimeout
FcgidMaxProcessesPerClass
FcgidMinProcessesPerClass
FcgidIdleTimeout
FcgidProcessLifetime

Source: apache.org

Other Directives will still required the Old Method below.

How to implement on cPanel

We will need to create a custom apache .conf file in the correct directory so that cPanel will build httpd.conf properly and include our configs.

Create the necessary directory for the site in question:
mkdir -p /usr/local/apache/conf/userdata/std/2_4/username/domain.tld/

note: the std directory will reflect the vhost type, std is port 80 vhosts and ssl is port 443 vhosts
note: the 2_4 directory will reflect the Apache version being used, it may be 2_2 or 2_0
Any file ending in .conf within that directory will be included as part of this user's vhost entry in httpd.conf

Create the config file you will be working with:
   touch /usr/local/apache/conf/userdata/std/2_4/username/domain.tld/fcgi.conf

Edit the file and add the appropriate directives you need to customize like:

<IfModule mod_fcgid.c>
    FcgidIOTimeout 1800
    FcgidBusyTimeout 1800
</IfModule>

note: Always use IfModule statements when possible to increase compatibility.

note: You can test your syntax with
httpd -t -f /path/to/file
to confirm your config.

Save the file and have cPanel rebuild the httpd.conf
 cp /usr/local/apache/conf/httpd.conf{,.lwbkup}
 /scripts/rebuildhttpdconf
Restart Apache to activate the new config file.

Old Method

If you find yourself in a situation where you need to adjust FCGI directives on a per application level this can be accomplished with: FcgidCmdOptions

The following example usage syntax sets specific variables/directives whenever FCGI executes the script: /home/user/public_html/index.php

    FcgidCmdOptions /home/user/public_html/index.php \
    InitialEnv MAX_REQUESTS=2000 \
    MaxRequestsPerProcess 2000 \
    IOTimeout 9
InitialEnv MAX_REQUESTS=2000 Sets the shell variable MAX_REQUESTS to 2,000
MaxRequestsPerProcess 2000 Sets FcigMaxRequestsPerProcess to 2,000
IOTimeout 9 Sets FcgidIOTimeout to 9

At the time of this writing, the following table outlines what directives/variables can be set in this manner:

Option name and syntax Corresponding Directive
ConnectTimeout seconds FcgidConnectTimeout
IdleTimeout seconds FcgidIdleTimeout
InitialEnv name[=value] FcgidInitialEnv
IOTimeout seconds FcgidIOTimeout
MaxProcesses value FcgidMaxProcessesPerClass
MaxProcessLifeTime seconds FcgidProcessLifeTime
MaxRequestsPerProcess value FcgidMaxRequestsPerProcess
MinProcesses value FcgidMinProcessesPerClass

Unfortunately, this directive cannot exist within .htaccess files so you will need to add it to an appropriate location within an apache include file. (e.g. /usr/local/apache/conf/includes/pre_virtualhost_global.conf). It is also good practice to enclose these statements within IfModule statements to allow for a more portable configuration file.

Apache MPMs and PHP Handler Benchmarks

700px

Apache Event with FCGI Optimization Guide

  • Use Apache 2.4.12 with the Event MPM if possible
  • Use FCGI as the PHP handler
  • If possible, upgrade the server to PHP 5.5 or newer. In some cases this might not be possible, as some CMS still needs PHP 5.4, and will break with PHP 5.5. If the server is using PHP 5.4 and the customer doesn't want to upgrade to 5.5 / knows some sites will break, that's fine, leave PHP at 5.4.
  • Enable Zend OPcache for PHP 5.5 PHP 5.4 doesn't have a built in opcache like 5.5, which is why we suggest using PHP 5.5. If you can't use PHP 5.5 then I suggest utilizing Xcache or APC instead. Any type of opcode cache is better than none!
Do not assume that since PHP 5.5 is installed that OPcache is as well. This module must also be compiled in via EA.

Please make sure you are apply these settings in WHM if possible. If you do not know where this section is in WHM, please reference the image below.

400px

1GB Server

If the server already has PHP 5.5+, enable Zend OPcache. If it does not have PHP 5.5 then suggest upgrade to client, if upgrading is not possible, or will break websites, stick with PHP 5.4 and look into using Xcache or APC instead of opcache. Also, make sure that mod_fastcgi has been select in EasyApache, once that has been done you should be able to select FCGI as the PHP handler.

If the server is running PHP 5.5, modify the main php.ini file

vim /usr/local/lib/php.ini

Add this to the bottom of the ini file, then restart apache. The opcache.so extension should already exist on the server if PHP 5.5 is updated. The actual location of the extension is /usr/local/lib/php/extensions/no-debug-non-zts-20121212/opcache.so but to enable it all you should have to do is paste in the code below.

opcache.memory_consumption = 32
opcache.interned_strings_buffer = 8
opcache.max_accelerated_files = 7963
opcache.validate_timestamps = 0
opcache.revalidate_freq = 0
opcache.fast_shutdown = 1
opcache.enable = 1

The next step is to use Apache Event, don't worry about Apache settings, but make sure you use FCGI as PHP handler and set these limits to prevent the server from running out of memory. These settings are for apache event 2.4 and may not work for apache event 2.2. If that is the case and you run into errors when applying these settings you should remove any <prefork> or <worker> directives in /usr/local/httpd/conf/httpd.conf and also remove any <event> settings in pre_virtualhost_global.conf. Yep, that's right, the best way to optimize apache event is to not even try and optimize it!. The settings below are default settings, so if you can apply them please do so just so someone doesn't think there aren't optimizations in place.

Please use WHM Pre VirtualHost Include Editor to apply the FCGI and Apache settings. If you apply these settings to another includes file that's not visible via WHM, there may be issues down the road with conflicting settings.

Home » Service Configuration » Apache Configuration » Include Editor » Pre VirtualHost Include


If you don't want to use WHM to apply the tweaks, you can add the settings to the file below.

vim /usr/local/apache/conf/includes/pre_virtualhost_global.conf

Please find out how many cpanel accounts are on the server before you paste in these settings. (ls /var/cpanel/users | wc -w). If you are working on a 1GB server that has 25 cPanel accounts, then FcgidMaxProcesses 20 may not be enough. If there are 25 users, and 20 FCGI process slots, and websites 1 - 20 have been visited in the past minute, and someone requests website #21 that site will hang until one of the 20 FCGI processes dies off. If you notice that a server is acting like this you should raise FcgidMaxProcesses to a reasonable value, in this case 25 would be fine. If memory is limited and raising the value is not an option then you may want to lower the timeout settings like FcgidIdleTimeout, FcgidIdleScanInterval, and FcgidProcessLifeTime to half the values shown below.

##Apache Event Default Settings (overrides main httpd.conf)

KeepAlive               On
KeepAliveTimeout        2
MaxKeepAliveRequests    500
<IfModule event.c>
ThreadsPerChild         25
ServerLimit             16
MaxRequestWorkers       400
StartServers            6
MinSpareThreads         150
MaxSpareThreads         400
MaxRequestsPerChild     10000
</IfModule>

<IfModule mod_fcgid.c>
FcgidMaxRequestLen                      1073741824
FcgidOutputBufferSize                   1073741824
FcgidMinProcessesPerClass               0
FcgidMaxRequestsPerProcess              0
FcgidInitialEnv PHP_FCGI_MAX_REQUESTS   0
FcgidInitialEnv PHP_FCGI_CHILDREN       0
FcgidMaxProcesses                       20
FcgidMaxProcessesPerClass               10
FcgidFixPathinfo                        1
FcgidIdleTimeout                        3
FcgidBusyTimeout                        300
FcgidProcessLifeTime                    300
FcgidIOTimeout                          300
FcgidIdleScanInterval                   1
FcgidErrorScanInterval                  1
FcgidZombieScanInterval                 1
</IfModule>

2GB Server

vim /usr/local/lib/php.ini
opcache.memory_consumption = 64
opcache.interned_strings_buffer = 8
opcache.max_accelerated_files = 7963
opcache.validate_timestamps = 0
opcache.revalidate_freq = 0
opcache.fast_shutdown = 1
opcache.enable = 1

Please find out how many cpanel accounts are on the server before you paste in these settings. If you are working on a 2GB server that has 45 cpanel accounts, then FcgidMaxProcesses 40 may not be enough. If there are 45 users, and 40 FCGI process slots, and websites 1 - 40 have been visited in the past few seconds and someone requests website #41 that site will hang until one of the 40 FCGI processes dies off. If you notice that a server is acting like this you should raise FcgidMaxProcesses to a reasonable value, in this case 45 would be fine. If memory is limited and raising the value is not an option then you may want to lower the timeout settings like FcgidIdleTimeout, FcgidIdleScanInterval, and FcgidProcessLifeTime to half the values shown below. Setting those 3 timeouts to 5 seconds is acceptable, setting these to 1 second is not recommended unless you have no other option.

Please use WHM Pre VirtualHost Include Editor to apply the FCGI and Apache settings. If you apply these settings to another includes file that's not visible via WHM, there may be issues down the road with conflicting settings.

Home » Service Configuration » Apache Configuration » Include Editor » Pre VirtualHost Include


If you don't want to use WHM to apply the tweaks, you can add the settings to the file below.

vim /usr/local/apache/conf/includes/pre_virtualhost_global.conf


##Apache Event Default Settings (overrides main httpd.conf)

KeepAlive               On
KeepAliveTimeout        2
MaxKeepAliveRequests    500
<IfModule event.c>
ThreadsPerChild         25
ServerLimit             16
MaxRequestWorkers       400
StartServers            6
MinSpareThreads         150
MaxSpareThreads         400
MaxRequestsPerChild     10000
</IfModule>

<IfModule mod_fcgid.c>
FcgidMaxRequestLen                      1073741824
FcgidOutputBufferSize                   1073741824
FcgidMinProcessesPerClass               0
FcgidMaxRequestsPerProcess              0
FcgidInitialEnv PHP_FCGI_MAX_REQUESTS   0
FcgidInitialEnv PHP_FCGI_CHILDREN       0
FcgidMaxProcesses                       40
FcgidMaxProcessesPerClass               20
FcgidFixPathinfo                        1
FcgidIdleTimeout                        3
FcgidBusyTimeout                        300
FcgidProcessLifeTime                    300
FcgidIOTimeout                          300
FcgidIdleScanInterval                   1
FcgidErrorScanInterval                  1
FcgidZombieScanInterval                 1
</IfModule>

4GB Server

vim /usr/local/lib/php.ini
opcache.memory_consumption = 64
opcache.interned_strings_buffer = 8
opcache.max_accelerated_files = 7963
opcache.validate_timestamps = 0
opcache.revalidate_freq = 0
opcache.fast_shutdown = 1
opcache.enable = 1

Please use WHM Pre VirtualHost Include Editor to apply the FCGI and Apache settings. If you apply these settings to another includes file that's not visible via WHM, there may be issues down the road with conflicting settings.

Home » Service Configuration » Apache Configuration » Include Editor » Pre VirtualHost Include


If you don't want to use WHM to apply the tweaks, you can add the settings to the file below.

vim /usr/local/apache/conf/includes/pre_virtualhost_global.conf


Please find out how many cpanel accounts are on the server before you paste in these settings. If you arer working on a 4GB server that has 65 cpanel accounts, then FcgidMaxProcesses 60 may not be enough. If there are 65 users, and 60 FCGI process slots, and websites 1 - 60 have been visited in the past few seconds and someone requests website #61 that site will hang until one of the 60 FCGI processes dies off. If you notice that a server is acting like this you should raise FcgidMaxProcesses to a reasonable value, in this case 65 would be fine. If memory is limited and raising the value is not an option then you may want to lower the timeout settings like FcgidIdleTimeout, FcgidIdleScanInterval, and FcgidProcessLifeTime to half the values shown below. Setting those 3 timeouts to 5 seconds is acceptable, setting these to 1 second is not recommended unless you have no other option.

##Apache Event Default Settings (overrides main httpd.conf)

KeepAlive               On
KeepAliveTimeout        2
MaxKeepAliveRequests    500
<IfModule event.c>
ThreadsPerChild         25
ServerLimit             16
MaxRequestWorkers       400
StartServers            6
MinSpareThreads         150
MaxSpareThreads         400
MaxRequestsPerChild     10000
</IfModule>

<IfModule mod_fcgid.c>
FcgidMaxRequestLen                      1073741824
FcgidOutputBufferSize                   1073741824
FcgidMinProcessesPerClass               0
FcgidMaxRequestsPerProcess              0
FcgidInitialEnv PHP_FCGI_MAX_REQUESTS   0
FcgidInitialEnv PHP_FCGI_CHILDREN       0
FcgidMaxProcesses                       80
FcgidMaxProcessesPerClass               40
FcgidFixPathinfo                        1
FcgidIdleTimeout                        3
FcgidBusyTimeout                        300
FcgidProcessLifeTime                    300
FcgidIOTimeout                          300
FcgidIdleScanInterval                   1
FcgidErrorScanInterval                  1
FcgidZombieScanInterval                 1
</IfModule>

8GB Server

vim /usr/local/lib/php.ini
opcache.memory_consumption = 64
opcache.interned_strings_buffer = 8
opcache.max_accelerated_files = 7963
opcache.validate_timestamps = 0
opcache.revalidate_freq = 0
opcache.fast_shutdown = 1
opcache.enable = 1

Please use WHM Pre VirtualHost Include Editor to apply the FCGI and Apache settings. If you apply these settings to another includes file that's not visible via WHM, there may be issues down the road with conflicting settings.

Home » Service Configuration » Apache Configuration » Include Editor » Pre VirtualHost Include

If you don't want to use WHM to apply the tweaks, you can add the settings to the file below.

vim /usr/local/apache/conf/includes/pre_virtualhost_global.conf

Please find out how many cpanel accounts are on the server before you paste in these settings. If you arer working on a 8GB server that has 85 cpanel accounts, then FcgidMaxProcesses 80 may not be enough. If there are 85 users, and 80 FCGI process slots, and websites 1 - 80 have been visited in the past few seconds and someone requests website #81 that site will hang until one of the 80 FCGI processes dies off. If you notice that a server is acting like this you should raise FcgidMaxProcesses to a reasonable value, in this case 85 would be fine. If memory is limited and raising the value is not an option then you may want to lower the timeout settings like FcgidIdleTimeout, FcgidIdleScanInterval, and FcgidProcessLifeTime to half the values shown below. Setting those 3 timeouts to 5 seconds is acceptable, setting these to 1 second is not recommended unless you have no other option.

##Apache Event Default Settings (overrides main httpd.conf)

KeepAlive               On
KeepAliveTimeout        2
MaxKeepAliveRequests    500

<IfModule event.c>
ThreadsPerChild         25
ServerLimit             16
MaxRequestWorkers       400
StartServers            6
MinSpareThreads         150
MaxSpareThreads         400
MaxRequestsPerChild     10000
</IfModule>

<IfModule mod_fcgid.c>
FcgidMaxRequestLen                      1073741824
FcgidOutputBufferSize                   1073741824
FcgidMinProcessesPerClass               0
FcgidMaxRequestsPerProcess              0
FcgidInitialEnv PHP_FCGI_MAX_REQUESTS   0
FcgidInitialEnv PHP_FCGI_CHILDREN       0
FcgidMaxProcesses                       160
FcgidMaxProcessesPerClass               80
FcgidFixPathinfo                        1
FcgidIdleTimeout                        3
FcgidBusyTimeout                        300
FcgidProcessLifeTime                    300
FcgidIOTimeout                          300
FcgidIdleScanInterval                   1
FcgidErrorScanInterval                  1
FcgidZombieScanInterval                 1
</IfModule>

16GB Server+

vim /usr/local/lib/php.ini
opcache.memory_consumption=64
opcache.interned_strings_buffer=8
opcache.max_accelerated_files=7963
opcache.validate_timestamps=0
opcache.revalidate_freq=0
opcache.fast_shutdown=1
opcache.enable=1

Please use WHM Pre VirtualHost Include Editor to apply the FCGI and Apache settings. If you apply these settings to another includes file that's not visible via WHM, there may be issues down the road with conflicting settings.

Home » Service Configuration » Apache Configuration » Include Editor » Pre VirtualHost Include


If you don't want to use WHM to apply the tweaks, you can add the settings to the file below.

vim /usr/local/apache/conf/includes/pre_virtualhost_global.conf


##Apache Event Default Settings (overrides main httpd.conf)

KeepAlive               On
KeepAliveTimeout        2
MaxKeepAliveRequests    500
<IfModule event.c>
ThreadsPerChild         25
ServerLimit             16
MaxRequestWorkers       400
StartServers            6
MinSpareThreads         150
MaxSpareThreads         400
MaxRequestsPerChild     10000
</IfModule>

<IfModule mod_fcgid.c>
FcgidMaxRequestLen                      1073741824
FcgidOutputBufferSize                   1073741824
FcgidMinProcessesPerClass               0
FcgidMaxRequestsPerProcess              0
FcgidInitialEnv PHP_FCGI_MAX_REQUESTS   0
FcgidInitialEnv PHP_FCGI_CHILDREN       0
FcgidMaxProcesses                       320
FcgidMaxProcessesPerClass               160
FcgidFixPathinfo                        1
FcgidIdleTimeout                        3
FcgidBusyTimeout                        300
FcgidProcessLifeTime                    300
FcgidIOTimeout                          300
FcgidIdleScanInterval                   1
FcgidErrorScanInterval                  1
FcgidZombieScanInterval                 1
</IfModule>

Troubleshooting and Caveats

.user.ini

Since PHP 5.3.0 for use with CGI/FastCGI

You can add single configuration modifications rather than recreating a whole php.ini for a user in current supported versions of php:

Using the [".user.ini"] configuration in the given DocumentRoot, since version PHP 5.30, will allow for adding only the modification required; this is ideal.

Only certain INI directives can be set in .user.ini files

https://secure.php.net/manual/en/configuration.file.per-user.php

"Only INI settings with the modes PHP_INI_PERDIR and PHP_INI_USER will be recognized in .user.ini-style INI files."

http://www.php.net/manual/en/ini.list.php

For example, you cannot disable functions in .user.ini as disable_functions is listed as "php.ini only".

Using a Custom / Local php ini changes with FCGI on cPanel

If the php version is 5.3+ it is recommended you use a .user.ini file in the given DocumentRoot. http://php.net/manual/en/configuration.file.per-user.php

Make sure that the additional files are going to be scanned:

<source lang='bash'> [root@attar ~]# php -i | grep additional Scan this dir for additional .ini files => /usr/local/lib/php.ini.d </source>

If this is not enabled and you are on fCGI, in the file /var/cpanel/easy/apache/rawopts/all_php5 add the following compile time option, and recompile PHP via an EasyApache:

<source lang='bash'> --with-config-file-scan-dir=/usr/local/lib/php.ini.d </source>

Next, in the folder /usr/local/lib/php.ini.d create a file named cPanel account name + .ini. In that file, put the following:

<source lang='text'> [PATH=/path/to/domain/doc/root] </source>

And you can put whatever you want under the PATH section. This will cover both www and non-www, however you can alternatively use the HOST directive here instead.

For example, If someone decided he wants to use the Phoenix timezone for his domain -

<source lang='text'> [root@attar /usr/local/lib/php.ini.d]# cat sharedtest1mikej.ini [PATH=/home/sharedtest1mikej/public_html] date.timezone = "America/Phoenix" </source>

Other possible additions: <source lang='text'> memory_limit = 128M </source>

This is a custom php.ini, and a server wide change

And finally, restart Apache:

For CentOS7: <source lang="bash"> systemctl restart httpd.service </source>

For CentOS6-: <source lang="bash"> service httpd restart </source>

mod_userdir not working

Mod_userdir will not work with FCGI. So if a customer needs to be able to use Mod_userdir you will need to use suphp. Ideally we would only use suphp while the customer tests out the site, then change it back over. There might be a way to make just that single vhost use suphp, but for now just change the handler back to suphp if you notice this issue.


https://documentation.cpanel.net/display/EA/EasyApache+Change+Log

As of the latest changelog for EasyApache, mod_userdir and FCGI appear to be compatible now.

In WHM Home »Security Center »Apache mod_userdir Tweak

  • Note also need to exclude protection on nobody user if enabling mod_userdir ability on a per user basis

Alternative

As an alternative to mod_userdir, I outlined some instructions for setting up and supporting a cPanel DNS Based Preview Address for an Enterprise Customer that would work on any cPanel server as well. This can be utilized by any customer who needs to have a reliable preview address system but cannot use mod_userdir.

Apache.org Special Considerations

Source: http://httpd.apache.org/mod_fcgid/mod/mod_fcgid.html

There are a few caveats outlined on the apache.org mod_fcgid page under the PHP Special Considerations header. I've outlined these concerns below and how to address them.

APC

"The popular APC opcode cache for PHP cannot share a cache between PHP FastCGI processes unless PHP manages the child processes. Thus, the effectiveness of the cache is limited with mod_fcgid; concurrent PHP requests will use different opcode caches."

I recommended not using APC specifically but instead use Zend Opcache or APCu when running mod_fcgid. As a bonus Zend Opcache is now compiled into PHP 5.5 by default but is available through PECL for older version should the customer not want to move forward with upgrading PHP to 5.5: [http://pecl.php.net/package/ZendOpcache]

APCu is a fork of the original APC that can be fully utilized when running mod_fcgid which can be installed as well should the customer absolutely need APC for some reason. However, it's probably best to stick with Zend Opcache since that is the direction PHP wants to go.

Periodic 500 Internal Server Error

"By default, PHP FastCGI processes exit after handling 500 requests, and they may exit after this module has already connected to the application and sent the next request. When that occurs, an error will be logged and 500 Internal Server Error will be returned to the client. This PHP behavior can be disabled by setting PHP_FCGI_MAX_REQUESTS to 0, but that can be a problem if the PHP application leaks resources. Alternatively, PHP_FCGI_MAX_REQUESTS can be set to a much higher value than the default to reduce the frequency of this problem. FcgidMaxRequestsPerProcess can be set to a value less than or equal to PHP_FCGI_MAX_REQUESTS to resolve the problem."

To resolve this particular issue you want to make sure that the PHP_FCGI_MAX_REQUESTS directive always matches the FcgidMaxRequestsPerProcess directive. This way there is never a discrepancy between PHP and Fcgid. You can use the following additions to your Apache include file to correct this problem, this sets both directives to 5k requests:


   FcgidInitialEnv PHP_FCGI_MAX_REQUESTS 5000
   FcgidMaxRequestsPerProcess 5000 


PHP Child Management

"PHP child process management (PHP_FCGI_CHILDREN) should always be disabled with mod_fcgid, which will only route one request at a time to application processes it has spawned; thus, any child processes created by PHP will not be used effectively. (Additionally, the PHP child processes may not be terminated properly.) By default, and with the environment variable setting PHP_FCGI_CHILDREN=0, PHP child process management is disabled."

You should rarely encounter this issue as the default value for PHP_FCGI_CHILDREN is 0. However some situation may occur where this has been configured for a different value. LightSpeed for instance defaults this environment variable to 1. You can fix this value to 0 should you suspect the setting is not set to 0 already by appending the following to your include file:

   FcgidInitialEnv PHP_FCGI_CHILDREN 0

Plesk

Fcgi comes preinstalled with Plesk 10+, and can be enabled in the domain's settings page under the "Websites & Domains" page.

File:Plesk-domain-page.png


Troubleshooting

FCGI limits can be adjusted in /etc/httpd/conf.d/fcgid.conf

[warn] [client 69.16.222.43] mod_fcgid: read data timeout in 60 seconds

This error can be corrected by raising IPCCommTimeout, raise as needed (120, 240, 360)
[warn] mod_fcgid: can't apply process slot for /home/beastman/public_html/index.php

This happens when MaxProcessCount (now named FcgidMaxProcesses) directive maximum is reached, raise as necessary but be careful of system memory
[warn] (103)Software caused connection abort: mod_fcgid: ap_pass_brigade failed in handle_request function

The following error is usually ignorable and is caused by a request being cancelled when passed to FCGI, however, you may need to raise the TimeOut value.
 
[warn] [client 68.183.51.58] mod_fcgid: HTTP request length 139264 (so far) exceeds MaxRequestLen (131072), referer: http://www.domain.tld/path/name/file.php?argument=data

Raise the MaxRequestLen directive when experiencing request length exceeding MaxRequestLen
'MaxRequestLen 150000' to /etc/httpd/conf/includes/pre_virtualhost_global.conf  **May need to be added to /etc/httpd/conf.d/fcgid.conf instead**

PHP cannot write to session files. With FCGI enabled you may see errors in the domains error_log regarding session files.

[Mon Jan 26 15:44:01 2015] [warn] [client 67.41.96.1] mod_fcgid: stderr: PHP Warning:  Unknown: Failed to write session data (files). Please verify that the current setting of session.save_path is correct (/var/lib/php/session) in Unknown on line 0, referer: http://missiontable.org/project/episode-1-everyone-is-a-missionary/

This is caused by incorrect permissions on the session directory. To fix:

chown apache:psacln /var/lib/php/session
chmod 770 /var/lib/php/session
chmod g+s /var/lib/php/session

You may also need to remove the existing session files to resolve permission conflicts.

Execute HTML code

To execute .html code that has PHP in it using the FCGI handler try adding the following code snippet to the htaccess

<IfModule mod_fcgid.c>
       <Files ~ (\.html)>
               SetHandler fcgid-script
               FcgidWrapper /usr/local/cpanel/cgi-sys/php5 .html
               Options +ExecCGI
               allow from all
       </Files>
</IfModule>

MultiPHP commands

The following will let you run version specific commands for use with multiphp

scl enable ea-php71 'COMMAND GOES HERE'