I want to run a PHP script from the command line, but I also want to set a variable for that script.
Browser version: script.php?var=3
Command line: php -f script.php
(but how do I give it the variable containing 3?)
I want to run a PHP script from the command line, but I also want to set a variable for that script.
Browser version: script.php?var=3
Command line: php -f script.php
(but how do I give it the variable containing 3?)
If you want to keep named parameters almost like var=3&foo=bar (instead of the positional parameters offered by $argv) getopt() can assist you.
Besides argv (as Ionut mentioned), you can use environment variables:
E.g.:
In test.php:
Script:
Command:
Also, take a look at using PHP from the command line.
A lot of solutions put the arguments into variables according to their order. For example,
will put the 5 into the first variable and 7 into the next variable.
I wanted named arguments:
so that I can use them as variable names in the PHP code.
The link that Ionuț G. Stan gave at http://www.php.net/manual/en/features.commandline.php
gave me the answer.
sep16 at psu dot edu:
You can easily parse command line arguments into the $_GET variable by using the parse_str() function.
It behaves exactly like you'd expect with cgi-php.
This will set $_GET['a'] to '1' and $_GET['b'] to array('2', '3').
As well as using argc and argv as indicated by Ionut G. Stan, you could also use the PEAR module Console_Getopt which can parse out unix-style command line options. See this article for more information.
Alternatively, there's similar functionality in the Zend Framework in the Zend_Console_Getopt class.