In this article, Jason will explain what CLI and Cron are and how to use them together within the PHP environment.
What is PHP CLI?
CLI stands for command line interpreter. What does this do for you? This allows you to run your PHP scripts at command line similar to Perl or any other scripting language used in *nix command line environment.
Why PHP CLI?
There a several advantages why one would want the ability to run PHP at command line
No need to learn another scripting language such as Perl, Bash or Awk
Ability to reuse existing components. For example say you’ve written a set of database access objects or functions you now can re-use them instead of re-writing them in Perl, Java or some other language.
Cross-platform, you can easily run PHP on *nix environment or windows environment or in fact any OS with PHP CLI installed
Making GUI applications, this is out of scope for this article visit http://gtk.php.net to learn more about PHP and desktop applications.
One may ask why do I need to run PHP at command line in the first place? I’m a web developer. Lots of times when making and running web applications with database functionality you will probably find yourself in position where you need to regularly clean up the database tables.
Another example maybe you need to send out regular web reports generated by your application to the appropriate administrators. Whatever the case may be, rather then trying to remember to run these tedious tasks on a regular basis isn’t it better to have a batch process where these tasks are automatically done at specified times. This is where you would use Cron and now that you know the advantages of using PHP at command line these two make a great pair.
There really isn’t much too it, it is just a matter of using the 2 different technologies together. The following sections will introduce you to both PHP CLI and Cron. After it will be pretty clear how to use them together, but incase you still don’t get it there is section demrating the use of PHP and Cron.
How to Install PHP CLI
Pre-Installed / Package Manager
If you are using Linux distribution with PHP already pre-installed or if you are using a package manager such as RPM you may have to do some fishing around to find the PHP executable. Mostly likely its under /usr/bin, as friendly reminder you might want to run the find command to find the PHP executable. Navigate you way to the root of your file system and type in the following find . -name php -print 2>&1 /dev/null.
Install from Using tar/source
For those of you who like to install from source, it is almost the same as installing PHP with apache except without APXS. To install PHP CLI you need to install it purely as CGI and with the –enable-cli option included. For those of you who still want to use PHP for the web you will have to install a separate installation of PHP.
Everything should work fine because with the APXS Apache when compiled with the right options will know where to find the PHP APXS version and for the other version of PHP all you have to do is set the correct PATH to access the PHP CLI version at command line. Here is step-by-step install of PHP CLI
Download the latest stable release of PHP
$ tar- xvzf php-version.tar.gz
$ cd php-version/
--enable-cli
--bindir=/usr/bin
. any other options you normally put, for example –with-mysql if you are going to use mySQL database with PHP
$ make
$ make install
Note –bindir indicates where you want the PHP binary to be installed
Hello World
Create a test file called phpcli.php. This file will contain a simply your standard hello world
#!/usr/bin/php -q
<?php
echo "Hello World with PHP CLI";
?>
Change the permission on the file to be executable, chmod 755 phpcli.php or chmod +x phpcli.php
Now run it, assuming you are in the same directory and the Path is indeed set for /usr/bin.
Hello World with PHP CLI
$
You will notice the difference from web php script there is the line #!/usr/bin/php, this indicates that the PHP executable is used to parse the file.
Reading in Command Line Arguments
Like most scripting languages you are able to pass in command line arguments. Create a file named testargs.php
#!/usr/bin/php -q
<?php
echo "Test Read Arguements:nn";
echo $_SERVER["argc"];
echo "n";
echo $_SERVER["argv"][0];
?>
$_SERVER[“argc”] will give the number arguments enter including. Note the script itself is an argument.
$_SERVER[“argv”] is an array of arguments. To access the first argument it will be at index 1, $_SERVER[“argv”][1]. Remember the file name itself is at index 0, $_SERVER[argv”[0].
Notice as well now that we aren’t making a web script we need to apply CLI specific code in this case to indicate next line we type in the escape character followed by n. Instead of
which is normally used for html.
More Hello World
Another way to run php at command line is directly right at the command line, for example
$ php -r "echo 'Hello World'";
Hello World
$
Getting more Help with PHP CLI
Type in the php executable with the switch -h, php -h. It should output something similar to the following:
Usage: php [options] [-f] <file> [args…]
php [options] -r <code> [args…]
php [options] [– args…]
-s Display colour syntax highlighted source.
-w Display source with stripped comments and whitespace.
-f <file> Parse <file>.
-v Version number
-c <path>|<file> Look for php.ini file in this directory
-a Run interactively
-d foo[=bar] Define INI entry foo with value ‘bar’
-e Generate extended information for debugger/profiler
-z <file> Load Zend extension <file>.
-l Syntax check only (lint)
-m Show compiled in modules
-i PHP information
-r <code> Run PHP <code> without using script tags <?..?>
-h This help
args… Arguments passed to script. Use — args when first argument starts with – or script is read from stdin
What is Cron?
Cron is basically a daemon used to initiate timed events. As mentioned before a great use of this is to cleanup a set a database tables at a specified time. It is usually automatically installed by default with most Linux distributions.
How to Use Cron?
To access Cron simply type crontab -e, this usually invokes VI the default editor used to open crontab text file. To change the default editor simply edit the /etc/.bash_profile then find the line that says editor=vi and change it to your favorite editor; for example, editor=emacs, editor=jove or editor=pico. Along with crontab -e, creation of crontab entry there is crontab -l which will display the contents of the crontab file and crontab -r will clear the contents of the current crontab file.
There may or may not be already entries in the file. To add a new Cron entry you first need to understand what the file layout is. The first set of numbers indicates the time to initiate or trigger the job the second part after the numbers is the process or task you want to run at the specified time.
The first six fields (the time) are defined as follows
An example of what a crontab entry looks like
0 2 1 * * echo "Hello World" 2>&1 /dev/console
This will output Hello World to the console at 2 am the first day of every month. The * is a wildcard, meaning to match all values. You can also specify a set and range of times. Taking the same example, say you want to execute now at 2am and 2pm. The entry would look like this
0 2,14 1 * * echo "Hello World" 2>&1 /dev/console
Notice the comma indicates more then one time for that field. Say now wanted Hello World to output every hour from 2am to 2pm the entry could look like this
0 2-14 1 * * echo "Hello World" 2>&1 /dev/console
PHP and Cron
This is actually quite easy now that you know how to use both PHP CLI and Cron. It is just a matter of using them together. Referring to the Hello World php script phpcli.php, assuming resides it /home/phpscripts. Simply add an entry into Cron invoking this process everyday at 1 pm, the entry should like the following:
0 13 * * * /usr/bin/php -f /home/phpscripts/phpcli.php
Future of PHP
PHP CLI and how PHP CGI will be invoked maybe changed in the future and possible can affect your use of PHP. It has been said php CGI binary will be renamed to php-cgi and the php CLI will be just php. There has been talk as well just to leave the way is or even merge the both CLI and CGI into one.
The main reason why CLI needs to be included into PHP by default is because PEAR requires the PHP binary to run. For more information visit the PHP website, http://www.php.net.
Tips
When making entries into Cron make a note of what user you doing this with. The Cron job may not run properly if the right permission is not assigned. As well make sure if your PHP script is accessing any external programs such as Sendmail that I has the proper permissions as well.
Other things to look out for are the environment settings. For example, if the PHP script is accessing Java classes you may have to wrap the PHP script with a shell script. Where the shell script includes the appropriate settings for both the Java Path and Classpath.
If accessing $_SERVER[“argv”] and $_SERVER[“argc”] do not work for you may want to try simply accessing the variables $argv and $argc, register globals need to be set on. This mostly like the case for older version of PHP.
*First published at DevArticles.com
Jason is a wireless and open source developer enthusiast who enjoys creating synergy and sharing knowledge in the software development world. To learn more about him visit his personal site at http://www.jasonlam604.com/