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
1 2 3 4 |
if(isset($_GET['name'])) { echo "My name is ".$_GET['name']; } |
Now same script I will run on command line it will through me an error.
Run Command:
1 |
Php test.php?name=ahsan |
Output:
1 |
Could not open input file: test.php?name=ahsan |
To avoid above error we use $argv. Let’s create another example for command line.
1 2 3 4 |
if(isset($argv[1])) { echo "My name is ".$argv[1]; } |
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.
Output:
1 |
Php test.php ahsan |
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.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 |
<?php $getInterface = php_sapi_name(); if($getInterface == 'cli') { if(isset($argv[1])) { echo "My name is ".$argv[1]; } } else { if(isset($_GET['name'])) { echo "My name is ".$_GET['name']; } } ?> |
Also read: