Pass a variable to a PHP script running from the command line
These lines will convert the arguments of a CLI call like php myfile.php "type=daily&foo=bar"
into the well known $_GET
-array:
if (!empty($argv[1])) {
parse_str($argv[1], $_GET);
}
Though it is rather messy to overwrite the global $_GET
-array, it converts all your scripts quickly to accept CLI arguments.
See parse_str for details.
If you want the more traditional CLI style like php myfile.php type=daily foo=bar
a small function can convert this into an associative array compatible with a $_GET
-array:
// Convert $argv into associative array
function parse_argv(array $argv): array
{
$request = [];
foreach ($argv as $i => $a) {
if (!$i) {
continue;
}
if (preg_match('/^-*(.+?)=(.+)$/', $a, $matches)) {
$request[$matches[1]] = $matches[2];
} else {
$request[$a] = true;
}
}
return $request;
}
if (!empty($argv[1])) {
$_GET = parse_argv($argv);
}
Using the getopt() function, we can also read a parameter from the command line. Just pass a value with the php
running command:
php abc.php --name=xyz
File abc.php
$val = getopt(null, ["name:"]);
print_r($val); // Output: ['name' => 'xyz'];
Just pass it as normal parameters and access it in PHP using the $argv
array.
php myfile.php daily
and in myfile.php
$type = $argv[1];
The ?type=daily
argument (ending up in the $_GET
array) is only valid for web-accessed pages.
You'll need to call it like php myfile.php daily
and retrieve that argument from the $argv
array (which would be $argv[1]
, since $argv[0]
would be myfile.php
).
If the page is used as a webpage as well, there are two options you could consider. Either accessing it with a shell script and Wget, and call that from cron:
#!/bin/sh
wget http://location.to/myfile.php?type=daily
Or check in the PHP file whether it's called from the command line or not:
if (defined('STDIN')) {
$type = $argv[1];
} else {
$type = $_GET['type'];
}
(Note: You'll probably need/want to check if $argv
actually contains enough variables and such)