How to check if one parameter is given:
if ($argc < 2 )
{
exit( "Usage: program <parameter1>\n" );
}
process( $argv[1] );
$argv — 传递给脚本的参数数组
包含当运行于命令行下时传递给当前脚本的参数的数组。
Note: 第一个参数总是当前脚本的文件名,因此 $argv[0] 就是脚本文件名。
Note: 这个变量仅在 register_argc_argv 打开时可用。
Example #1 $argv 范例
<?php
var_dump($argv);
?>
当使用这个命令执行:php script.php arg1 arg2 arg3
以上例程的输出类似于:
array(4) { [0]=> string(10) "script.php" [1]=> string(4) "arg1" [2]=> string(4) "arg2" [3]=> string(4) "arg3" }
How to check if one parameter is given:
if ($argc < 2 )
{
exit( "Usage: program <parameter1>\n" );
}
process( $argv[1] );
An easier way to populate $_GET with $argv values.
<?php
if ( isset( $argv ) ) {
parse_str(
join( "&", array_slice( $argv, 1 )
), $_GET );
}
?>
When you pass an option to the file that intercept the request, it will be transformed into an array item, and the option name will be lost. Only its content is captured.
<?php
var_dump($argv);
?>
call : "php file.php --test=foo baz"
will print
array(3) {
[0] =>
string(16) "file.php"
[1] =>
string(3) "foo"
[2] =>
string(3) "baz"
}
Sometimes $argv can be null, such as when "register-argc-argv" is set to false. In some cases I've found the variable is populated correctly when running "php-cli" instead of just "php" from the command line (or cron).
Improves on hamboy75's note by providing better support for positional arguments:
foreach ($argv as $arg) {
$e=explode("=",$arg);
if(count($e)==2)
$_GET[$e[0]]=$e[1];
else
$_GET[]=$e[0];
}
var_dump($_GET);
Using this modification, arguments without an = are treated as positional (this is not web standard but generally works).
To use $_GET so you dont need to support both if it could be used from command line and from web browser.
foreach ($argv as $arg) {
$e=explode("=",$arg);
if(count($e)==2)
$_GET[$e[0]]=$e[1];
else
$_GET[$e[0]]=0;
}
If your script is read from standard input or with the -r option, $argv[0] will be "-".
If you use the "--" option to separate PHP's arguments from your script's arguments, $argv[1] will be "--" if your script is read from a file. But if your script is read from standard input or with the -r option, the "--" will be removed.
Please note that, $argv and $argc need to be declared global, while trying to access within a class method.
<?php
class A
{
public static function b()
{
var_dump($argv);
var_dump(isset($argv));
}
}
A::b();
?>
will output NULL bool(false) with a notice of "Undefined variable ..."
whereas global $argv fixes that.
If you come from a shell scripting background, you might expect to find this topic under the heading "positional parameters".