Php pass arguments command line

I've recently received some comments on a previous article I wrote about scheduling PHP scripts using Cron that were asking how to pass parameters to the script. In this article I look at a number of different methods this can be done.

Note that if register_argc_argv is disabled [set to false] in php.ini, these methods will not work.

First lets see what will 100% not work. If you're used to passing command line parameters to a PHP script in a web browser using a query parameter [and then looking it up using $_GET], you may be trying to do something like this...

Of course PHP will promptly reject this with an error like this...

The reason that happens is because PHP is looking for a file called "script.php?param1=value1" but the script is actually called "script.php". The file system is not a web server so it doesn't know how to handle query parameters. A different approach is required.

Lets look at the 'classic' method to pass command line parameters to a script - using $argc and $argv.

Here's a PHP script that displays all of the command line arguments that were passed to it...

To pass command line arguments to the script, we simply put them right after the script name like so...

The output produced is...

Note that the 0th argument is the name of the PHP script that is run. The rest of the array are the values passed in on the command line. The values are accessed via the $argv array. This approach works, but it is very simplistic and doesn't play well if you're looking to transition from a query parameter way of passing in values to your script. With this approach there is no way to give names the the command line arguments being passed in.

If you want to be able to assign variable names for the values being passed in, getopt[] is the way to do it. Lets look at a different version of the script now...

Lets run this script like this...

The output produced is...

There are some major differences here. First with getopt[] you must specify which command line argument you want to retrieve. In the case of this script, it looks for the "-p" argument, that's specified by the "p:" value passed to getopt[]. The colon [:] means that the parameter must have a value. If you're used to doing something like "script.php?p=value1" this is an equivalent for the command line.

It's possible to pass multiple values in as well e.g.

In this case, the value changes to an array, so it's important to check the value type before using it.

If you want to pass in multiple differently named parameters e.g. "p" and "q", you change the getopt[] call like this...

Then running the script like this...

...produces this output...

The above way of using getopt[] limits your to using single character parameter names, what if you wanted to use a parameter name like "name"? This is also possible, we just change getopt[] call to this...

When using long parameter names, the way that the PHP script is run changes slightly, in this case we pass the parameter like so...

The output is then...

This can be expanded to multiple differently named parameters too. Passing the same named parameter multiple times also results in the value being of an array type, same as described earlier. It is also possible to pass values with a space in them by putting them in quotes.

This article doesn't cover all of the possibilities with getopt[] but it gives a starting point and hopefully now you can convert your script that uses the usual query parameters with $_GET to something that uses one of the approaches outlined above.

-i

I want to pass parameters from PHP Command Line Interface, and then read in the values using PHP script, something like this:


I pass the variable from CLI like this:

C:\xampp\php\php.exe name.php Robby

The above works, I get Robby as the output.

But I want to do something like this:

C:\xampp\php\php.exe name.php -inputFirstName="Robby"

So that the user is well informed to enter the correct parameters in the correct places. What is the appropriate way to parse these parameters?

asked Jun 15, 2012 at 10:20

0

When calling a PHP script from the command line you can use $argc to find out how many parameters are passed and $argv to access them. For example running the following script:


Like this:-

php script.php arg1 arg2 arg3

Will give the following output

int[4]
array[4] {
  [0]=>
  string[21] "d:\Scripts\script.php"
  [1]=>
  string[4] "arg1"
  [2]=>
  string[4] "arg2"
  [3]=>
  string[4] "arg3"
}

See $argv and $argc for further details.

To do what you want, lets say

php script.php arg1=4

You would need to explode the argument on the equals sign:-

list[$key, $val] = explode['=', $argv[1]];
var_dump[array[$key=>$val]];

That way you can have whatever you want in front of the equals sign without having to parse it, just check the key=>value pairs are correct. However, that is all a bit of a waste, just instruct the user on the correct order to pass the arguments.

worbel

6,47912 gold badges51 silver badges63 bronze badges

answered Jun 15, 2012 at 10:38

vascowhitevascowhite

17.8k9 gold badges58 silver badges76 bronze badges

4

I use this fairly concise method:

if[$argc>1]
  parse_str[implode['&',array_slice[$argv, 1]], $_GET];

Which would handle a call such as:

php script.php item1=4 item2=300

By sending it into $_GET you automatically handle web or CLI access.

For commentary, this is doing the following:

  • If the count of arguments is greater than one [as first item is the name of the script] the proceed
  • Grab the arguments array excluding first item
  • Turn it into a standard query string format with ampersands
  • use parse_str to extract to the $_GET array

answered Jul 6, 2013 at 15:19

NickMNickM

1911 silver badge2 bronze badges

While the answer is correct and you could do the parsing by hand, PHP also offers the getopt[] function that might actually provide useful here.

There's also object-oriented alternatives [written in PHP, available in a number of libraries] that might turn out to be what you need. Googling for "php getopt" will yield helpful results.

answered Jun 15, 2012 at 12:19

1

The getopt[] function is probably the most correct answer in the case of the question. Especially since it was made platform independent with PHP 5.3. In the particular case of this question and parsing multiple parameters, one way to leverage this function would be as follows:

$defaultValues = array["inputFirstName" => ""];
$givenArguments = getopt["", array["inputFirstName:"]];
$options = array_merge[$defaultValues, $givenArguments];
$inputFirstName = $options['inputFirstName'];

The call to set $inputFirstName with the value "Robby" would be:

> php script.php --inputFirstName="Robby"

Explanation

Default values for all expected parameters are set in the $defaultValues array. Input sent through via command line arguments are collected by PHP's getopt function and stored by the $givenArguments. Note that the colon [:] at the end of the "inputFirstName:" string indicates that this is a required argument. Without a colon here, only the presence of the argument would be detected, not the actual value [more information in the PHP Manual]. Merging these two arrays together on the third line results in array with all expected parameters being set with either default values or arguments provided from the command line/terminal if they are available.

Ovidiu

1211 silver badge10 bronze badges

answered Oct 25, 2017 at 11:54

bnp887bnp887

4,4402 gold badges25 silver badges30 bronze badges

you can send parameters as one argument then parse that argument like a $_GET array

C:\xampp\php\php.exe name.php "inputFirstName=Robby&LastName=John"

and in your PHP file

if [!empty[$argv[1]]] {
  parse_str[$argv[1], $_GET];
}

you'll get arguments in $_GET array like usual

answered Apr 5, 2020 at 12:50

MasMas

1,2391 gold badge13 silver badges13 bronze badges

I don't know if at the time this question has being asked what i going to answer to it was available but if you call php-cgi -f myfile.php var=something you can retrieved whit $var=$_GET['var']; from the command line then you don't have to change your code to call it from the web browser or the command line

answered Mar 28, 2021 at 19:05

denn0ndenn0n

4510 bronze badges

If you don't mind using a library, I suggest you take a look at The Console Component by Symfony.

It can be used to create command line applications and supports the use of Arguments & Options.

The documentation page contains a couple of excellent examples to get you started.

Of course under the hood it uses the same techniques as explained by vascowhite.

answered Jun 19, 2018 at 9:22

You can parse the user input on your program looking for specific strings such as -inputFirstName="x" [using regular expressions, for example] and then set the correct variable to x.

answered Jun 15, 2012 at 10:26

ÁlvaroÁlvaro

2691 silver badge9 bronze badges

How do I pass a command line argument in PHP?

To pass command line arguments to the script, we simply put them right after the script name like so... Note that the 0th argument is the name of the PHP script that is run. The rest of the array are the values passed in on the command line. The values are accessed via the $argv array.

What is $argv in PHP?

$argv — Array of arguments passed to script.

Can you run PHP from command line?

However, PHP does allow you to install it and run scripts on your local machine with no web access needed. Running PHP from Windows command line can be especially useful when trying to rapidly develop custom scripts, or to read and modify local files. In the example, we will use a custom PHP iterator.

Can we use PHP to write command line scripts?

There are two variables you can use while writing command line applications with PHP: $argc and $argv..
Telling PHP to execute a certain file. ... .
Pass the PHP code to execute directly on the command line..

Chủ Đề