Personal.X-Istence.com

Bert JW Regeer (畢傑龍)

FastCGI quick and dirty

In this quick and dirty guide for FreeBSD I will assume you have already compiled and installed PHP5 with fcgi mode enabled, which can be checked by running:

/usr/local/bin/php-cgi --version

I will also assume you have installed mod_fastcgi from www/mod_fastcgi in the ports.

Create the fast cgi ipc temp dir, make sure you place this somewhere it will keep existing:

cd /var/tmp
mkdir -p /var/tmp/fcgi-ipc/dynamic
chmod -R 0777 /var/tmp/fcgi-ipc

Let's create the directory where we are going to place our PHP wrapper, this config is for server wide using the same FastCGI PHP config. This is on purpose, since it will allow server wide PHP usage. If you want you could then split it up into virtualhosts if one required a standalone php running for that.

mkdir /usr/local/www/fastcgi-bin/
chmod 755 /usr/local/www/fastcgi-bin/</pre>

Next up we create the very simple wrapper

cat << EOF > /usr/local/www/fastcgi-bin/php5.fcgi
#!/bin/sh
# To use your own php.ini, comment the next line and uncomment the following one
#PHPRC="/usr/local/etc"
export PHPRC
PHP_FCGI_CHILDREN=8
export PHP_FCGI_CHILDREN
exec /usr/local/bin/php-cgi
EOF

Set PHP_FCGI_CHILDREN to whatever value you want, that is how many processes it will use. I suggest the standard which is 8, if you make it more, you use more ram, you make it less Apache will have to wait if all of the PHP processes are in use.

Next up, make it executable:

chmod +x /usr/local/www/fastcgi-bin/php5.fcgi

Last but not least, edit httpd.conf and make sure to add a comment in front of the mod_php5 line, and uncomment the mod_fastcgi line. Then add this to the end of your Apache config:

<IfModule mod_fastcgi.c>
    FastCgiIpcDir /var/tmp/fcgi-ipc/
    FastCgiConfig  -pass-header HTTP_AUTHORIZATION

    AddHandler  fastcgi-script              .fcgi .fcg .fpl

    Action      application/x-httpd-php5    /fastcgi-bin/php5.fcgi
    AddType     application/x-httpd-php5    .php .php5
</IfModule>

ScriptAlias /fastcgi-bin/ "/usr/local/www/fastcgi-bin/"
<Location /fastcgi-bin/>
    Options ExecCGI
    SetHandler fastcgi-script
    Order allow,deny
    Allow from all
</Location>

That's it. Restart apache and watch as the first time you access a PHP script FastCGI will spawn several of them, and they start serving requests. Load usage may seem higher, that is because unlike Apache the standalone running PHP's handle the jobs as they come in with whatever one is first, Apache will try to put as much work in one of it's preforked modules. As the PHP processes come and go through FastCGI the memory usage will go up and down. Mine has an average of about 300 MB, which is very good compared to the 800 MB Apache with mod_php would rack up.