Issue
I am on a shared server. When passing arguments to a crob job as below:
10 * * * * /usr/bin/php /home/website/cron/my_script.php country_id=10
This works withing the php script to get the value of the country_id:
$country_id = $_GET['country_id'];
This doesn't work and country_id is null:
$country_id = $argv[1]
My understanding is that the first option should not work and the second option should, however it the the other way around.
Can anyone give me an idea as to why?
Solution
HTTP and CLI are completely different environments.
If you want to adapt your script so it runs without changes in either environment, you can indeed get data from country_id=10
but you need to parse it yourself since it isn't a standard format that PHP expects. You can use parse_str(), but you need to ensure you're actually following the same encoding rules that you'd follow in an actual URL:
if (isset($argv[1])) {
parse_str($argv[1], $_GET);
}
var_dump($argv, $_GET);
If you want to write a command-line script that behaves more traditionally you can use getopt() and call it like e.g.:
/usr/bin/php /home/website/cron/my_script.php --country_id=10
/usr/bin/php /home/website/cron/my_script.php --country_id 10
$params = getopt('', ['country_id:']);
var_dump($params);
Answered By - Álvaro González Answer Checked By - Marilyn (WPSolving Volunteer)