From what I see, you are trying to pass an argument to the PHP script that runs on the command line.
On command line, not used $_GET
to access arguments from a script. You must use the variable $argv
to access these arguments.
Passing and accessing the arguments
Create a file cmd.php
, do the following:
print_r($argv);
Run on command line:
>>> php cmd.php 1 2 3
The result will be:
Array
(
[0] => cmd.php
[1] => 1
[2] => 2
[3] => 3
)
Note that the first argument from $argv
is the name of the running script. That’s always so.
If you want to get only the arguments after the script, you can use array_slice
, thus:
print_r(array_slice($argv, 1))
When you run a script
php via command line, each item separated by a space after php
is considered an argument of the command.
I mean, you’re not gonna use the interrogation ?
as you do in the case of browser query strings.
But what if I want to pass an argument that has space?
If you want to pass an argument that contains a literal space, you can use the quotes to delimit the argument.
Thus:
>>> php cmd.php "olá mundo"
Upshot:
Array
(
[0] => cmd.php
[1] => olá mundo
)
And if I want to quote as an argument?
Then you have to escape with the \
.
Example:
>>> php cmd.php "olá \""
Upshot:
Array
(
[0] => cmd.php
[1] => olá "
)
And before you ask me "How to escape the bar too", I say just use another bar.
Example:
>>> php cmd.php \\My\\Namespace
Exit:
Array
(
[0] => cmd.php
[1] => \My\Namespace
)
Count of past arguments
To count the number of arguments, you can also use the variable $argc
.
Create a file count_args.php
to test and place the following:
print_r($argc)
Run on command line:
>>> php count_args.php 1 2 3 4
The result will be:
5
Nothing prevents you from using count($argv)
to tell the arguments.
thanks, I got it!
– Alan PS