Pass command line argument to PHP

The command line arguments are stored in an array in the $_SERVER variables called ‘argv’. Running the command “php index.php test1 test2” and then doing print_r($_SERVER[‘argv’]) would output this:
[php]
Array
(
[0] => index.php
[1] => test1
[2] => test2
)
[/php]
You can also use $argv, It has return the same value. $argc variable to find the count of parameters passing in the command line argument.

Sample code used to pass argument form command line
[php]
<?php

if (isset($_SERVER[‘argc’])) {
if ($argc != 5)
die("Usage: index.php <username> <password> <receiver> <message>\n");

$username = $argv[1];
$password = $argv[2];
$receiver = $argv[3];
$message = $argv[4];
}

?>
[/php]

run the application

php index.php username password receiverno “TEST MSG FROM USER”

Permanent link to this article: https://blog.openshell.in/2012/07/pass-command-line-argument-to-php/

Leave a Reply

Your email address will not be published.