Universal PHP “spawn-fcgi” WrapperClass

spawn-fcgi utility, lighttpd, virtual hosting, a3non::platform application

Why don’t use the spawn script from the lighttpd wiki ?#

Is Shell scripting so bad ? Well i dont’t like it when using it in complex environments. Currently i am building the A3non::Platform application (a simple, managed webhosting platform) and need some php cli based utilities to spawn php-fcgi processes via the famous spawn-fcgi tool of lighttpd. Formerly i used an shell script like this from the lighttpd wiki but i don’t like to call a script with another one. So here is the pure php way!

Usage#

Spawning a new PHP FCGI process via php cli is just easy like this:

[php]
// the path to store the user php.ini file, the fcgi socket and the pid file
define(‘FCGI_USER_DIR’, ‘/var/www/fcgi’);

// the path to the spawn-fcgi binary
define(‘SPAWNFCGI_PATH’, ‘/usr/bin/spawn-fcgi’);

// the path to the php binary
define(‘PHP_FCGI_PATH’, ‘/usr/local/bin/php-cgi’);

// spawn cgi processes – the $user array contains some user specific params
FCGI::spawn(array(
‘PHPRC’ => FCGI_USER_DIR.’/’.$user[‘userName’].’/php.ini’,
‘MAX_REQUESTS’ => $user[‘fcgi_max_requests’],
‘SOCKET’ => FCGI_USER_DIR.’/’.$user[‘userName’].’/phpfcgi.socket’,
‘USER’ => $user[‘userName’],
‘GROUP’ => $user[‘userName’],
‘CHILDREN’ => $user[‘fcgi_children’],
‘PIDFILE’ => FCGI_USER_DIR.’/’.$user[‘userName’].’/phpfcgi.pid’,
‘PROGRAM’ => PHP_FCGI_PATH,
‘PROGRAM_ARGS’ => ”
));

[/php]

A3non::Platform FCGI Class#

[php]
class FCGI{
public static function spawn($args){
// param array
$p = array();

// escape args
foreach ($args as $key=–>$value){
$p[$key] = escapeshellarg($value);
}

// spawn the fcgi processes
return shell_exec(‘env -i – ‘
.’ FCGI_WEB_SERVER_ADDRS=127.0.0.1′
.’ PHPRC=’.$p[‘PHPRC’]
.’ PHP_FCGI_MAX_REQUESTS=’.$p[‘MAX_REQUESTS’]
.’ ‘.SPAWNFCGI_PATH
.’ -s ‘.$p[‘SOCKET’]
.’ -u ‘.$p[‘USER’]
.’ -g ‘.$p[‘GROUP’]
.’ -C ‘.$p[‘CHILDREN’]
.’ -P ‘.$p[‘PIDFILE’]
.’ -M 0770′
.’ — ‘.$p[‘PROGRAM’]);
}

public static function unspawn($pidfile){
if (file_exists($pidfile)){
shell_exec(‘kill $(cat ‘.$pidfile.’)’);
shell_exec(‘rm ‘.$pidfile);
return true;
}else{
return false;
}
}
}
[/php]