Using PHP from the command line
Written by Graham Clarke   
Thursday, 15 January 2009 05:14

Why use PHP from the command line?  I'm much more facile with PHP than Perl or Awk, so using PHP to tie together several tasks needed to update about 50 sites on one of our servers was very appealing.  Here's a simple CLI PHP example that prints any arguments added to the command line.

 

#!/usr/bin/php -q
<?php
echo "Test Arguments:\n";
print_r($_SERVER["argv"]);
?>

Run the above code from the command line like this

./test.php orange apple

will output the following

./test.php
Array
(
    [0] => ./test.php
    [1] => orange
    [2] => apple
)

What's really great is that you can use your existing PHP tool box.  Need to access a database?  Just include PEAR::MDB2 like in a web app and viola! Need to execute a shell command from within your PHP script just use shell_exec().  

So maybe CLI PHP isn't as sexy as having a bunch of shell scripts or Perl scripts, but I like to be as efficient as possible and being able to use PHP for server admin tatsks is pretty nice.

Links

http://www.php.net/features.commandline


blog comments powered by Disqus
 

Copyright 2000 - by 53 Technology. All Rights Reserved.