Passing Variables to PHP Scripts from the Command Line
When executing PHP scripts via the command line, such as through crontab, it's useful to pass variables to the script for customization and control. However, the traditional method of appending query parameters to the script's path, like php myfile.php?type=daily, may not work.
The $argv Array
For command-line execution, PHP provides the $argv array, which contains arguments passed to the script. The first element, $argv[0], is the script's filename. Subsequent elements, starting from $argv[1], contain the additional arguments.
Passing Arguments Via $argv
To pass the type argument in this case, simply call the script as follows:
php myfile.php daily
Within the PHP script, you can then retrieve the argument using $argv[1]:
$type = $argv[1];
Web Page Consideration
If your PHP script is also used as a web page, you'll need to distinguish between command-line and web access. One approach is to check if STDIN is defined, which typically indicates command-line execution:
if (defined('STDIN')) { $type = $argv[1]; } else { $type = $_GET['type']; }
Alternatively, you can use a shell script and Wget to access the script via the web from the command line:
#!/bin/sh wget http://location.to/myfile.php?type=daily
By understanding the use of $argv and considering web access, you can effectively pass variables to PHP scripts running from the command line.
The above is the detailed content of How do I pass variables to a PHP script executed from the command line?. For more information, please follow other related articles on the PHP Chinese website!