Setting up cron

Crons can pass parameters or arguments to scripts as well for example you have example.php set as cron like below

/usr/bin/php -q /home/usrname/example.php

Now if you want to pass parameters to example.php in cron you can do it as follow by using key value pairs

/usr/bin/php -q /home/usrname/example.php id=123 email=test@example.com name=username

If you want to send arguments without keys you can send them as follow

/usr/bin/php -q /home/usrname/example.php 123 test@example.com username

Receiving parameters in php

Remember that $_GET or $_POST only work when php script is called from browser.
So in cron it is actually called directly from command line so no $_GET or $_POST will work here.

When script is called by command line the parameters are passed into $argv array. So $argv is the array that contains all the parameters passed to cron.

If you var_dump the $argv you will get following (if you passed key value)

array(4) {
  [0]=>
  string(27) "/home/usrname/example.php"
  [1]=>
  string(6) "id=123"
  [2]=>
  string(22) "email=test@example.com"
  [3]=>
  string(13) "name=username"
}

And if you passed parameters without keys you will get as follow

array(4) {
  [0]=>
  string(27) "/home/usrname/example.php"
  [1]=>
  string(3) "123"
  [2]=>
  string(16) "test@example.com"
  [3]=>
  string(8) "username"
}

If you passed parameters by keys you will need to use parse_str function to get key and value in array, for example if you want to get email parameter you will get it as follow

parse_str($argv[2], $param2);
echo $param2['email']; 
//it will print test@example.com

And if you are using it by values only then its pretty simple

echo $argv[2]; 
//it will print test@example.com
Advertisements