How to get command line arguments in PHP?

PHP has the getopt() function for getting options or command line arguments from a CLI PHP script. This provides a simple way to get values from the command line like e.g. “-a foo”. This post looks at how to do this. More details can be found in the PHP getopt() manual page.

$_SERVER[‘argv’]

The command itself (i.e. your script filename) and the command line arguments are stored in an array in the $_SERVER variables called ‘argv’. It is possible to access the command line arguments from here but it’s easier to getopt() because you can then access the arguments by flag and in any order. Running the command “php myscript.php foo bar” and then doing print_r($_SERVER[‘argv’]) would output this:

Array
(
    [0] => myscript.php
    [1] => foo
    [2] => bar
)

getopt() function

The getopt() function returns the list of command line arguments in an associative array. It returns the arguments passed in based on the parameters passed to it. For example, to get the values for the flags -a -b and -c you would do this:

$arguments = getopt("a:b:c:");

If you called the script like this (the first example has spaces between the flag and the value, the second has no spaces but both will return the values):

php myscript.php -a foo -b bar -c baz
OR
php myscript.php -afoo -bbar -cbaz

Then doing print_r($arguments) would return this:

Array
(
    [a] => foo
    [b] => bar
    [c] => baz
)

Note that the colons after the value are required; if you don’t use them and a flag is passed on the command line with that letter then it won’t be returned in the array.

Another thing to note is that if it one of the values you are looking for is not passed on the command line, then it won’t be added to the array return from getopt(). Calling the same $arguments = getopt(“a:b:c:”) script as in the above example, calling the script like so:

php myscript.php -a foo

and then doing print_r($arguments) would show this:

Array
(
    [a] => foo
)

Version used for this post

The version I used for testing with this post was PHP 5.1.6 on CentOS 5.0. According to the PHP manual page for getopt() on versions of PHP prior to 5.3 did not work. There is also an “optional” parameters option from 5.3 which doesn’t work as expected in the version 5.1.6 that I used, and a second parameter to the getopt() function for long options (in the style –name=value or –name value) which is not widely available prior to 5.3. On the CentOS system I was using, attempting to use the second paameter for long options resulted in this error message:

PHP Warning:  getopt(): No support for long options in this build in ...

Therefore if you are targeting systems with PHP installations prior to 5.3 you are best to stick with the short options only.

As you can see, the first argument is actually the name of your PHP script, which is consistent with many other languages that use this "ARGV" functionality. The other command line arguments are then shown after that.

Note that you can also access the PHP command line args as array elements, like this:

echo $argv[0];
echo $argv[1];

I hope this PHP command line arguments example is helpful. If you have any questions or comments, just use the form below.

For other tutorials on reading command line arguments from different programming languages, we have the following tutorials on our website:

Any PHP code that we write is usually run on the server when users request a webpage. However, it is also possible to run a script through a CLI or command-line interface. Sometimes it becomes necessary to write PHP scripts that can accept arguments when executed inside a command prompt. There can be a variety of reasons for doing this, ranging from ease of use to automation of specific tasks.

In this tutorial, you will learn how to access command-line arguments inside your script with

<?php
50 and
<?php
51 in PHP.

Why Do We Need Them?

Arguments are passed around as query parameters when you request a page from your web browser. On the server side, we access the values inside these parameters using the superglobal

<?php
52. Unfortunately, this technique won't work when you are running your script inside the command prompt. This is because a command prompt expects arguments for its script in a different format.

Let's create a simple script to better understand the problem. Put the following code inside a file called reverse.php.

1
<?php
2
3
$original = $_GET["name"];
4
echo strrev($original);
5
6
?>

Now, try to run the following command from the directory in which the file reverse.php is located.

1
<?php
1

This will give you an error similar to the following line.

1
<?php
3

This happens because the system tries to run a file called reverse.php?n=monty within the current directory, but there is no such file.

You can run the following command successfully, but it still won't output the reversed name.

1
<?php
5

It will show a warning about an undefined array key "n" instead. The use of

<?php
50 and
<?php
51 solves this problem for us.

Get Command-Line Arguments With <?php 50

There are two predefined variables in PHP, called

<?php
56 and
<?php
50, that you can use to work with command-line arguments.

The variable

<?php
56 simply tells you the number of arguments that were passed to the script. Remember that the name of the script you are running is always counted as an argument. This means that the minimum value of
<?php
56 would be 1.

The variable

<?php
50 is much more helpful because it is an array of arguments passed to the script and contains their actual value. You can iterate over all the values with a
<?php
61 loop.

Let's create a script to change the brightness and contrast of JPEG images. The script will accept three parameters besides its name: the name of the file, desired brightness, and desired contrast. Put the following code in a file called im-filters.php.

1
<?php
2
3
2
0
4
5
2
3
6
2
5
2
6
2
7
2
8
2
9
3
0
3
1
3
2
3
3
3
4
3
5
3
6
3
7
3
8
3
9
$original = $_GET["name"];
0
$original = $_GET["name"];
1
$original = $_GET["name"];
2
$original = $_GET["name"];
3
$original = $_GET["name"];
4
$original = $_GET["name"];
5
$original = $_GET["name"];
6
$original = $_GET["name"];
7
$original = $_GET["name"];
8
$original = $_GET["name"];
9
4
0
4
1
4
2
4
3
4
4
4
5
?>

We create an array with three elements and autofill it with

<?php
62. Now, we loop over the command-line arguments and put their values inside our
<?php
63 array. We have skipped the first argument because that's the name of the script itself. The name of the new file is created by adding -edited at the end of the original file name.

Now, run the following command in the terminal:

1
4
8

This should create the following output in the terminal, while generating a file called beach-edited.jpg.

1
echo strrev($original);
0

Get Command-Line Arguments With <?php 51

There are a few shortcomings in the method that we used to access command-line arguments in our previous example. For instance, we are assuming that the arguments will be provided in the order in which we are processing them in the script. However, that might not always be the case.

The

<?php
51 function in PHP is a great way for accessing all these arguments without worrying too much about their order, etc. It has one required parameter and two optional parameters.

  1. <?php
    
    66: Short options in the command line start with a single hyphen. Each character passed into this string is matched against the options passed to the script.
  2. <?php
    
    67: This optional parameter accepts an array. Each element (a string) in the array is matched against the options passed to the script starting with two hyphens.
  3. <?php
    
    68: The optional third parameter is used to store the index at which the parsing of arguments stopped.

Both

<?php
66 and
<?php
67 follow a specific convention to parse values passed to the script. Individual characters and strings don't accept any values. Characters and strings followed by a colon indicate a required value. Characters and strings followed by two colons indicate an optional value. Here are some examples:

  1. <?php
    
    71 and
    <?php
    
    72 will not accept any values. We will use them in our script to convert images to grayscale.
  2. <?php
    
    73 and
    <?php
    
    74 will both require a value passed to them. We will use them to make sure that users provide us an image file on which we can apply our filters.
  3. <?php
    
    75 and
    <?php
    
    76 will both accept an optional value. We will use them to give users the option to not change the contrast of the image unnecessarily. The same goes for
    <?php
    
    77 and
    <?php
    
    78.

One thing you should remember is that the array returned by

<?php
51 does not contain elements which were missing from the argument list. Also, the elements present in the argument list which did not have a specified value are set to
<?php
80.

Now it's time to create our script with all these points in mind.

1
<?php
2
3
echo strrev($original);
5
4
echo strrev($original);
7
5
echo strrev($original);
9
6
2
6
5
2
2
8
5
4
2
9
2
7
3
1
3
3
3
7
3
5
6
1
3
6
3
8
$original = $_GET["name"];
0
3
9
$original = $_GET["name"];
1
6
7
$original = $_GET["name"];
2
6
9
$original = $_GET["name"];
4
?>
1
$original = $_GET["name"];
6
2
7
$original = $_GET["name"];
7
$original = $_GET["name"];
9
?>
6
4
0
?>
8
4
2
<?php
00
4
4
<?php
02
4
5
2
7
<?php
05
<?php
06
<?php
07
<?php
08
<?php
09
<?php
10
<?php
11
<?php
12
<?php
13
<?php
14
2
7
<?php
16
<?php
17
<?php
18
<?php
19
<?php
20
4
1
<?php
22
4
3
<?php
24
<?php
25
?>

We accept four different arguments for our image editing script and have set only the filename to be required. The grayscale filter does not accept any parameter, so we have marked it as such.

We check if the value has been supplied with a long-form or short-form option for each of our arguments. The code inside the

<?php
81 block will execute in either case. After that, the ternary operator allows us to pick the correct form to get our value with a single statement. For example, let's say a user has provided a contrast value using the long-form option. In this case,
<?php
82 will be
<?php
80, and
<?php
84 will be set according to the value in
<?php
85.

The

<?php
86 string is used to keep track of all the filters applied to the image to show them to the user.

Try running the following command in the console now.

1
<?php
28

It should show you the following output:

1
<?php
30

Avoiding Script Duplication

We have seen that different code needs to be used to access argument values when the script runs on a web server vs. when it runs in a CLI. However, this does not mean that you will require two copies of the same script to run in different environments. There is a function called

<?php
87 that will tell you whether your code is running inside a web server or a CLI. The predefined constant
<?php
88 serves the same purpose.

1
<?php
2
3
<?php
35
4
<?php
37
5
<?php
39
6
<?php
41
2
6
2
7
2
8
2
9
<?php
46
3
1
3
3
?>

Final Thoughts

There are a lot of times when we have to write code that will work on some provided input to give us an output. Usually, the input is handled by

<?php
52 and
<?php
90 when the script is running on a server. However, you will sometimes need to run your script through a CLI, and that requires you to use
<?php
50 or
<?php
51. Using
<?php
51 gives you more flexibility when dealing with the arguments and does some heavy lifting regarding their parsing for you.

Try running the above script on your own images while changing the order of arguments. You should consider creating your own custom scripts to automate boring tasks with a task scheduler.

How do I get command line arguments?

Command-line arguments are given after the name of the program in command-line shell of Operating Systems. To pass command line arguments, we typically define main() with two arguments : first argument is the number of command line arguments and second is list of command-line arguments.

How to run command line in PHP?

You just follow the steps to run PHP program using command line..
Open terminal or command line window..
Goto the specified folder or directory where php files are present..
Then we can run php code using the following command: php file_name.php..

Can PHP be used for command line scripts?

There are two variables you can use while writing command line applications with PHP: $argc and $argv. The first is the number of arguments plus one (the name of the script running). The second is an array containing the arguments, starting with the script name as number zero ($argv[0]).

How to check syntax in PHP command line?

Use the php command with the -l option This command will detect any syntax errors in your script!