January 22, 2009

PHP! Taking arguments from Command Line

Setting up Command Line Interface SAPI for php
In *nix environment:
Since PHP 4.3.0 the both --enable-cli and --enable-cgi are enabled by default. If a module SAPI is chosen during configure, such as apxs, or the --disable-cgi option is used, the CLI is copied to {PREFIX}/bin/php during make install otherwise the CGI is placed there. If you want to override the installation of the CGI binary, use make install-cli after make install. Alternatively you can specify --disable-cgi in your configure line.
In windows:
PHP 5, the CLI is distributed in the main folder, named php.exe. The CGI version is distributed as php-cgi.exe.


Now consider this CLI hello world programme
File: cli-hello-world.co
<?php
fwrite(STDOUT,"CLI hello world \n");
?>

To call this script from command line (we assume that php bin path is set in OS environment variable )

>_ php cli-hello-world.com

CLI hello world


To passing an argument to php script from command line is similar to C or Java. There are two global variables $argc and $argv, that hold an integer value of number of arguments passed and an array of sting value of the arguments respectively.
Note: if no additional parameter is passed then the arg variables only will contain the file name and the value of $argc will be 1

For example
File : cli-arg.php
<?php
if($argc > 1)
{
foreach ($argv as $argumentVariable)
fwrite(STDOUT, $argumentVariable. "/n");
}
?>

Now we can call this script like
>_ php cli-arg.php "Hello World"
cli-arg.php
Hello World

In PHP 5, the CLI version will always populate the global $argv and $argc variables regardless of any php.ini directive setting. Even having register_argc_argv set to off will have no affect in CLI.



(c) Sourav Ray Creative Commons License

1 comment:

  1. Good article. It would definately help people trying to work on Command line arguments with PHP.

    Keep it up Sourav!!

    ReplyDelete