Cron Job Tutorial: Crontab Scheduling Syntax and Script Example

This is a beginner tutorial on using crontabs or cron jobs in your LAMP (Linux/Apache/MySQL and PHP) web hosting account. Crontabs can be used to automatically execute server side commands, such as a PHP script, at periodic intervals. You can specify these periodic intervals, whether you want the script to be executed hourly, daily, weekly, and so on.

Crontabs is very useful when doing website maintenance. You can use this feature for the following purposes:

  1. Deleting all files in a certain folder at regular intervals. If you accept user-uploaded files, then eventually it will clog your web hosting server. If you do not regularly delete these files, they will consume a lot of disk space and can slow down your website.
  2. Deleting files of a specific type at regular intervals. You can also choose to delete files of a specific type, instead of deleting all of the files in the folder. If you have PHP, HTML and MP3 files together inside the folder, you can delete only the MP3 files.
  3. Regularly backing up your MySQL database. This is one of the most important webmaster tasks. By using crontabs or the cron job feature, you can create a PHP script that will back up a selected MySQL database, and have it execute automatically executed at a specific, regular interval (e.g monthly, yearly, etc).

This tutorial will focus on creating a cron PHP script application, then configuring your cron hosting feature to execute these scripts automatically.

Deleting All Files Within a Folder using Cron

Let’s have an actual example. Below is the PHP script that will delete all of the files in the folder.

<?php
/*
First protect this file from direct access. If unauthorized users execute this script using a browser, then they will receive "Direct File Access Prohibited" Errors.
*/
if (‘deleteallfiles.php’ == basename($_SERVER['SCRIPT_FILENAME'])) {
die (‘<h2>Direct File Access Prohibited</h2>’);
}
else {
/*

If this is not a direct file access, execute the script. Next we define which folder to clean in your FTP server. Bear in mind that this is a full server path to the folder.
This should start with a forward slash and end with a trailing slash. To determine the full server path, you need to create a PHP file with this script and save it as fullserverpath.php:

<?php
echo $_SERVER['SCRIPT_FILENAME'];
?>

Then upload it inside the folder that you need to clean. Execute the script in the browser, e.g http://www.yourdomain.com/folderthistoclean/fullserverpath.php
You will see the full path to this folder, such as: /home/www/php-developer.org/testdelete/fullserverpath.php

This means that the full server path to the folder should be: /home/www/php-developer.org/testdelete/, then use this one to define $foldertodelete:

*/
$foldertodelete  = ‘/home/www/php-developer.org/testdelete/';

//Delete entire files in the folder , this is using *.*, this means all files.
$fileTypes1 = ‘*.*';
/*
Define how old the files in minutes should be when they are deleted. For example, if you set the expiration time to 3 minutes; this means that all files older than 3 minutes will be deleted by this script during cron execution.
*/

$expire_time1= 3;

//Find all files  in the folder using a loop

foreach (glob($foldertodelete . $fileTypes1) as $Filename1) {

/*
Read file creation time  using filectime function. Read more about this function here: http://php.net/manual/en/function.filectime.php

*/
$FileCreationTime1 = filectime($Filename1);

/*
Calculate file age in seconds. The difference between the current time and file creation time.
*/

$FileAge1 = time() – $FileCreationTime1;

//Is the file older than 3 minutes?

if ($FileAge1 > ($expire_time1 * 60)){
//If yes, then delete file.
unlink($Filename1);
}
}
}
?>
This is the complete script: http://www.php-developer.org/wp-content/uploads/scripts/deleteallfiles.txt

If you would like to delete files of a specific type, instead of all of the files in the folder, you can use this script: http://www.php-developer.org/wp-content/uploads/scripts/deletespecificfiles.txt

Bear in mind that the two above scripts can only delete files, and not a folder.

{mospagebreak title=Configuring Crontab to Automatically Run the Script}

First upload the PHP script to the root directory of your website. Then log in to your web hosting account. Go to the crontabs section. Bear in mind that different web hosting companies will have different methods for configuring cron.

For a common crontabs feature, such as that used by Agilityhoster and other hosting companies, take a look at the screen shot shown below:

Suppose you would like to implement the "file delete script" discussed previously, and you want to run it every 10 minutes, every hour of every day, every month, and every weekday.

First, enter the command (this is simply a full server path to the file delete script at the root directory):

/home/www/php-developer.org/deleteallfiles.php

Then, make sure the following items are highlighted:

  • Every 10 minutes
  • Every hour
  • Every day
  • Every month
  • Every weekday

Finally, click "Set Cron Job." When this is successful, you will receive a notice that the cron has been successfully created or added.

Screen shot:

Configure Cron Job in Go Daddy Hosting to Run PHP Scripts

Other web hosting companies, such as Go Daddy, offer a significantly different set up for setting or configuring cron jobs. If you have websites hosted in Go Daddy, follow the procedure below:

1. Log in to your web hosting account, and click "My Account."

2. Under "My Products," click "Hosting."

3. Under "Products == Web Hosting," click the "Launch" button for the website on which you would like to implement cron.

Clicking this will take you to the "Hosting Control Center."

4. In the hosting control center, go to "Content"  – "Cron Manager."

5. Click "Create Cron Job." You will then see a screen that looks like the image below:

6. Under "Cron Job title," you can assign a name to it, such as "Testcron."

7. In the "Command," Go Daddy requires the following command syntax for running PHP scripts using Cron Job:

For PHP 5 web hosting accounts:

/web/cgi-bin/php5 "$HOME/html/thisisyourphpscriptatrootdirectory.php"

For PHP 4 web hosting accounts:

/web/cgi-bin/php "$HOME/html/thisisyourphpscriptatrootdirectory.php"

Suppose you have a folder named "restricted" in your website root directory. And you would like to run a MySQL database backup script named backupmysql.php, which uses PHP 5.

Also you would like to run this backup script on an hourly basis (in reality you would set this up to run  monthly, perhaps).

This is how you will configure this cron:

Cron Job Title: Testcron
Command: /web/cgi-bin/php5 "$HOME/html/restricted/backupmysql.php"
Frequency: Hourly
Minute: x:00

Screen shot:

Securing Your Cron Scripts

The following are tips that can you use to secure your cron PHP scripts:

  1. Protect the script from direct browser execution. Of course you would not want your script to be run manually by public users using a web browser.
  2. Protect the script inside a folder that is denied public access. This will ensure that only the cron hosting feature can access it, but not public users or bots.
  3. If you are deleting files, double check the syntax and folder, because a single mistake can wipe out all of the files in your server.
  4. Remove unused cron commands, scripts and folders, because these, too, can clog and slow down your server.
[gp-comments width="770" linklove="off" ]
antalya escort bayan antalya escort bayan