Browse Category

PHP

Scheduling PHP Cron Jobs with Parameters

I was making a PHP script for reading a resource account’s calendar from an Exchange server and then saving the data to a MySQL database. This script was going to be a cron job on the web server set to run every 2 minutes, and I was going to have multiple cron jobs for reading different resource account calendars.

Instead of having separate cron files for reading each account, I made one cron_rooms.php file that I could use with the HTTP $_GET variable. The PHP script worked great through the web browser, and the URL was something like this: http://website.com/cron_rooms.php?room=[name]

To schedule the cron jobs, I added them easily through the webmin web control panel in the browser.

webminCron

To do it through command line in SSH, I’d run this command: crontab -u <username> -e

Then I’d enter the lines below for updating my 5 rooms every 2 minutes.

0,2,4,6,8,10,12,14,16,18,20,22,24,26,28,30,32,34,36,38,40,42,44,46,48,50,52,54,56,58 * * * * /usr/bin/php -q /var/www/cron_rooms.php?room=dsv #Update DSV
0,2,4,6,8,10,12,14,16,18,20,22,24,26,28,30,32,34,36,38,40,42,44,46,48,50,52,54,56,58 * * * * /usr/bin/php -q /var/www/cron_rooms.php?room=9991 #Update 9991
0,2,4,6,8,10,12,14,16,18,20,22,24,26,28,30,32,34,36,38,40,42,44,46,48,50,52,54,56,58 * * * * /usr/bin/php -q /var/www/cron_rooms.php?room=9992 #Update 9992
0,2,4,6,8,10,12,14,16,18,20,22,24,26,28,30,32,34,36,38,40,42,44,46,48,50,52,54,56,58 * * * * /usr/bin/php -q /var/www/cron_rooms.php?room=9993 #Update 9993
0,2,4,6,8,10,12,14,16,18,20,22,24,26,28,30,32,34,36,38,40,42,44,46,48,50,52,54,56,58 * * * * /usr/bin/php -q /var/www/cron_rooms.php?room=9994 #Update 9994

So anyway, all is good and ready to go, right?… Wrong!

When the cron job runs, it’s giving me these errors:

Could not open input file: /var/www/cron_rooms.php?room=dsv
Could not open input file: /var/www/cron_rooms.php?room=9991
Could not open input file: /var/www/cron_rooms.php?room=9992
Could not open input file: /var/www/cron_rooms.php?room=9993
Could not open input file: /var/www/cron_rooms.php?room=9994

Why was the script working in the browser, but not in cron? Simple, the script I made was using HTTP GET requests that works for URL’s. When running in command line mode (which is what cron is using) I need to pass the parameters using arguments.

Solution: I replaced the $_GET[‘room’] variable in my script with $argv[1]. Then change each line in cron from this:

/usr/bin/php -q /var/www/cron_rooms.php?room=[name]

to this:

/usr/bin/php -q /var/www/cron_rooms.php [name]

In command line mode, $argv[0] will always contain the path of the script: “/var/www/cron_rooms.php”

And $argv[1] would be the first argument after the path: [name]

If we had more arguments, we can access them with $argv[2], $argv[3], etc.