From what I see, you're trying to pass an argument to the PHP script that runs on the command line.
In the command line, $_GET
is not used to access arguments from a script. You should use the $argv
variable to access these arguments.
Passing and accessing the arguments
Create a file cmd.php
, do the following:
print_r($argv);
Run from the 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 of $argv
is the name of the script that is running. This is always so.
If you want to get only the arguments after the script, you can use array_slice
, like this:
print_r(array_slice($argv, 1))
When you run script
php via command line, each item separated by a space after php
is considered an argument of the command.
That is, you will not use the ?
query 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 quotation marks to delimit the argument.
So:
>>> php cmd.php "olá mundo"
Result:
Array
(
[0] => cmd.php
[1] => olá mundo
)
What if I want to pass quotation marks as an argument?
Then you have to escape with \
.
Example:
>>> php cmd.php "olá \""
Result:
Array
(
[0] => cmd.php
[1] => olá "
)
And before you ask me "How to escape the bar too", I anticipate you just use another bar.
Example:
>>> php cmd.php \My\Namespace
Output:
Array
(
[0] => cmd.php
[1] => \My\Namespace
)
Counting passed arguments
To count the number of arguments, you can also use the $argc
variable.
Create a count_args.php
file to test and put the following:
print_r($argc)
Run from the command line:
>>> php count_args.php 1 2 3 4
The result will be:
5
Nothing also prevents you from using count($argv)
to count the arguments.