Passing $_GET parameters to cron job Passing $_GET parameters to cron job php php

Passing $_GET parameters to cron job


The $_GET[] & $_POST[] associative arrays are only initialized when your script is invoked via a web server. When invoked via the command line, parameters are passed in the $argv array, just like C.

Contains an array of all the arguments passed to the script when running from the command line.

Your command would be:

* 3 * * * /path_to_script/cronjob.php username=test password=test code=1234 

You would then use parse_str() to set and access the paramaters:

<?phpvar_dump($argv);/*array(4) {  [0]=>  string(27) "/path_to_script/cronjob.php"  [1]=>  string(13) "username=test"  [2]=>  string(13) "password=test"  [3]=>  string(9) "code=1234"}*/parse_str($argv[3], $params);echo $params['code']; // 1234


Not a direct answer to your question but a better solution I think:

If you want nobody except cron to run the script, just place it outside the web-root. That way there is no access via the web-server at all.

If you do need to run the command as a special user as well, don't use GET but have a user login and check for a logged-in session (a certain set session variable...) and include the script in that page only.

Your publicly accessible script would look something like:

session_start();if (isset($_SESSION['user'])){  include '/path/to/script/outside/of/web-root';}else{  die('No access.');}


* 3 * * * /path_to_script/cronjob.php?username=test&password=test&code=1234

This will not work

* 3 * * * /path_to_script/cronjob.php username=test password=test code=1234

This works

Also, you need to use parse_str() function and get value

$str = "first=value&arr[]=foo+bar&arr[]=baz";parse_str($str);echo $first;  // valueecho $arr[0]; // foo barecho $arr[1]; // baz