How to pass $_GET to command line arguments in PHP (with example)

If your php script has a query strings then you can get values by using $_GET variable. But unfortunately $_GET not works in command line. Then how can we pass arguments to script on command line?

In this short tutorial I am going to show you how to pass arguments by using example.

In php there is a variable name as $argv that serves as an argument in command line by using $argv we can achieve this.

Below is the simple php script that gets $_GET[‘name’] and print message

Now same script I will run on command line it will through me an error.

Run Command:


To avoid above error we use $argv. Let’s create another example for command line.

You may notice that I used $argv[1] in above code but normally array starts with zero. [1] is an argument so $argv will always start with zero.


But what if I want to run test.php on browser and CLI then I have to create 2 separate files?

No not at all. Php has a built-in function php_sapi_name() that returns the type of interface between web server and php. So if you want run same code on both browser and CLI then your code will be.

Also read:


Posted in PHP

Leave a Reply

Your email address will not be published. Required fields are marked *