Integrating PHP Command Line Scripts with Existing Web Projects

After reading the post on Johan Mares site about the PHP command line interface, I thought I would indulge in the details how I’ve been using the PHP cli for some of my web based applications.

First, some of my web apps have multiple configuration files which are determined by the $_SERVER[‘HTTP_HOST’] value. If (stricmp( $_SERVER[‘HTTP_HOST’],’compiledweekly’) ) { // then I load compiledweekly config file }. So with that in mind, I had to add to the top of my cli scripts the following line:

$_SERVER[‘HTTP_HOST’] = ‘compiledweekly.com';

This required me to have to edit the command line script every time i used it with another site. Here’s the trick: pass arguments to your command line so your script can parse them. Here’s how I did it to also include a verbose mode.

	if( count($argv) > 1 )
	{
		for( $x = 1; $x < count($argv); $x++ )
		{
			switch($argv[$x])
			{
				case '--verbose': { // Print results to std out
					$Verbose = true;
				}; break;
				case '--host': { // Print results to std out
					$_SERVER['HTTP_HOST'] = trim($argv[$x+1]);
				}; break;
			}
		}
	}

	if( $Verbose ) echo "Starting script...nn";
	// Continue with your script below

So with the following example I can run my script for my compiledweekly.com site with verbose information. Example:

/path/to/script.php --verbose --host compiledweekly.com

Now if you use your php script in a cron task, don't include the --verbose and make sure you check the $Verbose flag before printing any results. Don't forget to add to the end of the command line " > /dev/null 2>&1" minus the quotes, this sends any std out and std error messages to a black hole.

If your command line script is saved in a web accessible folder, here's a line you should add to the top so no web browser can execute your script:

if( php_sapi_name() != 'cli' ) die('Access denied.');

This will take your command line apps to a new level while giving you the ability to use existing web code.

Leave a Reply