Leon Anavi
IT Tips && Tricks

PHP

Created: 27.08.2009 23:39 Last Modified: 27.08.2009 23:40 Views: 12458
Keywords: argc, argv, console

Develop Console Applications with PHP

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


  Home | About | Contact | Disclaimer | Sitemap © 2009-2022 Leon Anavi. All rights reserved.