Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to pass GET parameters on the command line

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.

like image 565
jack.linton Avatar asked Dec 11 '25 21:12

jack.linton


1 Answers

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