How to execute a PHP file via the command line and output the results
Today I am going to show you how to execute a PHP file via a command line interface and output the result to the terminal. You will also learn how to pass in arguments to the PHP file.
The first step is to test to see if the global "argv" variable is set. If it is, then we can run our program and get the array of arguments passed to our script.
if(isset($argv)) {
Side note, you can read the history behind ARGV here: https://flatironschool.com/blog/a-short-explanation-of-argv
The next step will be to slice our argument's array into a string and populate our $_GET array with the new key value variables we have passed in.
parse_str(
join( "&", array_slice( $argv, 1 )
), $_GET );
Lastly, we will print out the new array to see the results.
echo "\n";
print_r($_GET);
echo "\n";
}
To test this script you will need to find the full path to your command line PHP executable file. You can then open up a command line terminal. I used windows cmd utility for this example. The command example:
C:\xampp\php\php.exe C:\xampp\htdocs\test\run.php test1=a test2=b
Comments
Post a Comment