我在 Ubuntu 上,并且有一个我一直在尝试运行的小型备份脚本。不幸的是,它没有执行备份。我在这里包含了两个 PHP 脚本,以防我遗漏了一些东西。
首先,这是我的 crontab 的样子
*/30 * * * * /usr/bin/php /var/www/mybackup.php
上面的 cron 应该调用这个脚本:mybackup.php
<?php
include('myfunctions.php');
theBackup();
?>
主要脚本是这样的。虽然当我手动运行它时它工作得很好,但它不能用 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 );
}
}
?>
上面的代码有什么我遗漏的吗?就像我说的,当我从浏览器运行 mybackup.php 时,它运行良好,但不是通过 cron。
任何帮助将不胜感激。