You may be wondering how to pass variables to PHP script while running from command line. So this tutorial helps you to read command line arguments in PHP.
Query strings will work only in web browsers, so when using command line we should have a different approach.
$argv is the answer for this, it is the array of arguments passed to script.
See the below example is for command line execution of PHP script
tutsplanet $ : php mytest.php arg1 arg2 arg3
You just need to access the argv array in the mytest.php
#!/usr/bin/php <?php // loop through each element in the $argv array foreach($argv as $value) { echo "$value\n"; } ?>
This will print following output
mytest.php arg1 arg2 arg3
As you see in example first argument will be always the self PHP script.
Instead of this, you can get the value with array key. For example first argument will be $argv[1], second will be $argv[2].
Enjoy working with command line arguments in PHP
- Just want to thank us? Buy us a Coffee
- May be another day? Shop on Amazon using our links.
Your prices won't change but we get a small commission.
Leave a Reply