Question:
I'm trying to send GET parameters to a php using php's exec command, but when I put the parameters the script doesn't run, it doesn't reach the other php, follow my code:
exec.php:
$cmd = 'php teste.php?id=10,11';
$pid = exec($cmd.' > /dev/null &');
test.php:
$ids = $_GET["id"];
echo $ids;
I don't get error msgs.
Answer:
As I see it, you're trying to pass an argument to the PHP script that runs from the command line.
On the command line, you do not use $_GET
to access script arguments. You must use the $argv
variable to access these arguments.
Passing and accessing arguments
Create a cmd.php
file, 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 to $argv
is the name of the running script. This is always the case.
If you want to get just the arguments after the script, you can use array_slice
, like this:
print_r(array_slice($argv, 1))
When you run a php script
via the command line, each item separated by a space after php
is considered a command argument.
In other words, you won't use the interrogation ?
as you do for 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 quotation marks around the argument.
So:
>>> php cmd.php "olá mundo"
Result:
Array
(
[0] => cmd.php
[1] => olá mundo
)
What if I want to use quotes as an argument?
Then you have to escape with the \
.
Example:
>>> php cmd.php "olá \""
Result:
Array
(
[0] => cmd.php
[1] => olá "
)
And before you ask me "How to escape the bar too", I'll say that 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 $argc
variable.
Create a count_args.php
file to test and put in the following:
print_r($argc)
Run from the command line:
>>> php count_args.php 1 2 3 4
The result will be:
5
Nothing prevents you from using count($argv)
to count the arguments either.