Home > Enterprise >  How to pass a parameters on the command line?
How to pass a parameters on the command line?

Time:04-09

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.

CodePudding user response:

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";
}

CodePudding user response:

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

  • Related