Tuesday, August 27, 2013

PHP cron job in Windows



To run a PHP code daily in your Windows such as backup database and sending email notices etc, first create a file c:\cron\cron.php, for example:
<?php
require_once($web_root.'_includes/db_constants.inc.php');
require_once($web_root.'_includes/email_content.inc.php');
require_once($web_root.'_classes/PHPMailer_v2.0.0/class.phpmailer.php');

$db = @mysql_connect(DB_HOST . ':' . DB_PORT, DB_USER, DB_PASSWORD);
if (!$db) {
   $mail = new PHPMailer;
   $mail->From     = MAIL_CESEI_ADMIN;
   $mail->FromName = $_mail_from_name_cesei;
   $mail->AddAddress(MAIL_CESEI_ADMIN);
   $mail->Subject = 'Cron DB connect error';
   $mail->Body    = 'DB failure - @mysql_connect('.DB_HOST . ':' . DB_PORT.' '.DB_USER.' '.DB_PASSWORD.');';
   $mail->Send();
   unset($mail);
   exit;
}
if (!@mysql_select_db(DB_NAME, $db)) {
   $mail = new PHPMailer;
   $mail->AddAddress(MAIL_CESEI_ADMIN);
   $mail->Subject = 'Cron DB connect error';
   $mail->Body    = 'DB failure - @mysql_select_db('.DB_NAME.');';
   $mail->Send();
   unset($mail);
   exit;
}

?>
To run cron.php daily, using Windows scheduler.
Schedule task:
php c:\cron\cron.php
Schedule:
Daily start time 12:00 am every 1 day

No comments:

Post a Comment