Reputation: 77
I want to run a PHP program from a shell script, passing parameters each time and getting them with $_GET["DBF"]
.
For example:
$ php prog.php?DBF=clients
$ php prog.php?DBF=suppliers
How can I do this? The above syntax does not work.
Upvotes: 3
Views: 11461
Reputation: 1163
You can get all the arguments using the following code.
unset($argv[0]);
parse_str(implode('&',$argv),$_REQUEST);
All the arguments will be in the array $_REQUEST
, which can be used in the browser as well. You can basically use as many arguments as you like and use it the same ways as you would for a website.
You can use it this way:
php prog.php DBF=clients id=42
This will be in the array $_REQUEST
:
(
[DBF] => clients
[id] => 42
)
Upvotes: 2
Reputation: 53
The $_GET and $_POST variables are superglobals that are created only when PHP is being used to process web requests via a server like Apache.
If you are running PHP from the command line, you can add your variable "DBF" as an argument after the script name:
$ php prog.php clients
To access commandline variables, call the $argv variable, which is an array. The first item in the array is the name of the script, and the following items are whatever arguments you appended to the command line request:
array(2) {
[0]=>
string(8) "prog.php"
[1]=>
string(4) "clients"
}
Reference: https://www.php.net/manual/en/reserved.variables.argv.php
Upvotes: 2
Reputation:
You call a script with parameters like this:
php prog.php DBF=clients
No HTTP request is made, so $_GET
etc. will not be available. As stated in the PHP documentation for CLI usage $argv
will hold the parameters for your script.
$argv[0]
is the script name itself, $argv[1]
is the first parameter etc.
parse_str()
the parameter:
#!/usr/bin/php
<?php
// $argv[0] will hold the script name
// $argv[1] will hold the first argument
// print_r($argv[1]);
// parse the first argument
parse_str($argv[1], $arg);
// print_r($arg);
if(isset($arg['DBF']) && $arg['DBF'] == 'clients') {
// Do something for the clients
echo "Clients stuff";
echo "\n";
} else if(isset($arg['DBF']) && $arg['DBF'] == 'suppliers') {
// Do something for the suppliers
echo "Suppliers stuff";
echo "\n";
}
Upvotes: 5