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.

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

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

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:

to this:

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.