May the PHP Force Be with You
PHP is among the most popular languages for web application. Although PHP is slower than Perl, C or C++ it can also be a powerful tools for creation of console scripts due to it's simplicity and regular expressions. This article will explain how to write PHP console applications and will provide examples under Linux.
Console Scripts
To run a PHP script under console execute command php followed by the script name or add path to PHP at the beginning of the file.
Example under Linux
#!/usr/bin/php -q
<?
echo "Hello, World!\n";
?>
The -q is used to suppress HTTP headers.
[leon@localhost tests]$ chmod 755 hello.php
[leon@localhost tests]$ ./hello.php
Hello, World!
[leon@localhost tests]$
Make sure your user has priveleges before executing the script in order to avoid Permission denied.
Passing Arguments
Like any other console application PHP script can accept arguments. There are two predefined variables argc and $argv. The variable $argc is used to store the number of arguments passed to the script. Array named as $argv stores all arguments. The first argument, with index zero is name of the script.
Example
#!/usr/bin/php -q
<?
for($nIter = 0; $nIter < $argc; $nIter++)
{
echo "Argument {$nIter} is {$argv[$nIter]}\n";
}
?>
Output
[leon@localhost tests]$ ./console.php anavi.org
Argument 0 is ./console.php
Argument 1 is anavi.org
[leon@localhost tests]$
PHP Manual
$argc
$argv
|