I've written some simple PHP code to backup files daily, but while it works perfectly from the command line every time, I can't get it to work from within cron.
I've followed the troubleshooting steps suggested in:
Why is crontab not executing my PHP script? But this seems to deal with a more general case where PHP won't run at all. Having put debug messages into my php code so I can see that it runs fine from the command line, but $files = glob("*.mp4");
is getting no results when run from cron.
My crontab line is as below (added via sudo crontab -e
):
00 8 * * * timeout 23h /mnt/usbdrive/CCTV/192.168.0.24/webdav/sdcard/alarm/mvfiles.php
Please ignore the "ip address" in the above, it's just a folder name created by an old wget
command.
My php is below:
#!/usr/bin/php
<?php
$files = glob("*.mp4");
$movedFiles = 0;
$stringFiles = "";
foreach($files as $file) {
$year = substr($file,3,4);
$month = substr($file,7,2);
$day = substr($file,9,2);
$stringFiles .= "\n".$file .";";
/*
echo($file."\n");
echo($year."\n");
echo($month."\n");
echo($day."\n");
*/
if (!file_exists("/mnt/usbdrive/alarmBackup/" . $year)) {
mkdir("/mnt/usbdrive/alarmBackup/" . $year);
}
if(!file_exists("/mnt/usbdrive/alarmBackup/" . $year . '/' . $month)){
mkdir("/mnt/usbdrive/alarmBackup/" . $year . '/' . $month);
}
if(!file_exists("/mnt/usbdrive/alarmBackup/" . $year . '/' . $month . '/' . $day)){
mkdir("/mnt/usbdrive/alarmBackup/" . $year . '/' . $month . '/' . $day );
}
if(!file_exists("/mnt/usbdrive/alarmBackup/" . $year . '/' . $month . '/' . $day .'/'.$file)){
copy("/mnt/usbdrive/CCTV/192.168.0.24/webdav/sdcard/alarm/".$file, "/mnt/usbdrive/alarmBackup/" . $year . '/' . $month . '/' . $day .'/'.$file);
$movedFiles += filesize('/mnt/usbdrive/CCTV/192.168.0.24/webdav/sdcard/alarm/'.$file);
echo("copied ".$file."; total moved so far ".human_filesize($movedFiles) . "\n");
}
}
echo("lastly, ".human_filesize($movedFiles)."\n");
if(mail('me@hotmail.com','CCTV Archive Results','Hi Martin, today '.human_filesize($movedFiles).' of data were copied to the archive. \n The following files were checked:' . $stringFiles)){
echo("Mail Sent\n");
} else {
echo("Mail Not Sent\n");
}
function human_filesize($bytes, $decimals = 2) {
$size = array('B','kB','MB','GB','TB','PB','EB','ZB','YB');
$factor = floor((strlen($bytes) - 1) / 3);
return sprintf("%.{$decimals}f", $bytes / pow(1024, $factor)) . @$size[$factor];
}
?>
When run from the command line (using sudo mvfiles.php
)I get a long list of files in my email inbox (as I'd expect) and when run from cron I just get a mail saying:
Hi Martin, today 0.00B of data were copied to the archive. \n The following files were checked: