I'm on Ubuntu and have a small backup script I've been trying to run. Unfortunately, it's not executing the backup. I've included the two PHP scripts here in case there's something I'm missing.
First, here's how how my crontab looks like
*/30 * * * * /usr/bin/php /var/www/mybackup.php
The cron above supposed to call this script: mybackup.php
<?php
include('myfunctions.php');
theBackup();
?>
The main script is this. Although it works perfectly when I manually run it, but it does not run with cron.
<?php
/*
* Script to back up the database
*
*
*/
function getAllFiles($directory, $recursive = false) {
$result = array();
$handle = opendir($directory);
while ($datei = readdir($handle))
{
if (($datei != '.') && ($datei != '..'))
{
$file = $directory.$datei;
if (is_dir($file)) {
if ($recursive) {
$result = array_merge($result, getAllFiles($file.'/'));
}
} else {
$result[] = $file;
}
}
}
closedir($handle);
return $result;
}
function getOldestTimestamp($directory, $recursive = true, $display ='file') {
$allFiles = getAllFiles($directory, $recursive);
$highestKnown = time();
$highestFile = '';
foreach ($allFiles as $val) {
$currentValue = filemtime($val);
$currentFile = $val;
if ($currentValue < $highestKnown){
$highestKnown = $currentValue;
$highestFile = $currentFile;
}
}
if($display=='file'){
return $highestFile;
} else {
return $highestKnown;
}
}
function theBackup(){
$sendfrom = "System Backup <admin@domain.com>";
$headers = 'Admin <admin@domain.com>' . "\n";
$headers .= 'MIME-Version: 1.0' . "\n";
$headers .= 'Content-type: text/html; charset=iso-8859-1' . "\n";
$filename = getOldestTimestamp('./app/db/',true,'file');
$filename = str_replace("./app/db/", "", $filename );
$backupfile = '/var/www/app/db/'.$filename;
$handle = fopen($backupfile, 'w') or die('Cannot open file: '.$backupfile);
$dbhost = "localhost";
$dbuser = "user";
$dbpass = "password";
$dbname = "db";
if(system("mysqldump -h $dbhost -u $dbuser -p$dbpass $dbname > $backupfile") == false){
mail('email@yahoo.com','My Backup','Back Up successfully completed',$headers );
}else {
mail('email@yahoo.com','My Backup','Back Up did NOT complete successfully please check the file/folder
permission',$headers );
}
}
?>
Is there anything I'm missing from the code above? Like I said, when I run mybackup.php from the browser, it works perfectly, but not through cron.
Any help would be highly appreciated.