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?)
As of version 4.3. 0, PHP supports a new SAPI type (Server Application Programming Interface) named CLI which means Command Line Interface. As the name implies, this SAPI type main focus is on developing shell (or desktop as well) applications with PHP.
To pass command line arguments to the script, we simply put them right after the script name like so... Note that the 0th argument is the name of the PHP script that is run. The rest of the array are the values passed in on the command line. The values are accessed via the $argv array.
Introduction. When a PHP script is run from command line, $argv superglobal array contains arguments passed to it. First element in array $argv[0] is always the name of script. This variable is not available if register_argc_argv directive in php. ini is disabled.
Script:
<?php // number of arguments passed to the script var_dump($argc); // the arguments as an array. first argument is always the script name var_dump($argv);
Command:
$ php -f test.php foo bar baz int(4) array(4) { [0]=> string(8) "test.php" [1]=> string(3) "foo" [2]=> string(3) "bar" [3]=> string(3) "baz" }
Also, take a look at using PHP from the command line.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With