如何在 cron 作业中执行 php 脚本

how to execute php script in cron job

我想每天自动执行一个 PHP 脚本来制作数据库备份并将其发送到电子邮件。当我通过调用它的 URL 在我的网络浏览器中执行它时,一切都很好。但是当我在我的服务器中定义一个 Cron 作业时,我得到了这个错误:

sh: /Viana-BackupMailer/mehravar_news_20161204_192302.sql.gz: No such file or directory mysqldump: Got errno 32 on write X-Powered-By: PHP/5.4.45 Content-type: text/html

我在 cron 作业中使用以下命令:

php /home/mehravar/public_html/Viana-BackupMailer.php

这是我的 PHP 代码:

<?php 
    $TimeZone = "Asia/Tehran";              // Your location time zone
    $SiteName = "Mysite.com";               // Your site name
    $SiteTitle = "My Site Title";           // Your site title
    $DeleteBackup = false;                  // Delete Backup file after send it by email

    $DB_Server = "localhost";               // MySQL server name
    $DB_Name = "DB_Name";                   // MySQL database name
    $DB_Username = "DB_User";               // MySQL database Username
    $DB_Password = "DB_Pass";               // MySQL database Password

    $Mail_To = "myemail@email.com";         // Receiver email
    $Mail_From = "sender@email.com";        // Sender email (Your host email)

    $LogText = "";
    $StorageDir = "Viana-BackupMailer";
    if(!is_dir($_SERVER['DOCUMENT_ROOT']."/".$StorageDir)){
        mkdir($_SERVER['DOCUMENT_ROOT']."/".$StorageDir, 0755);
    }

    date_default_timezone_set($TimeZone);
    $BackupDate = date("Ymd_His");
    $LogDate = date("Ym");
    $Path = $_SERVER["DOCUMENT_ROOT"]."/".$StorageDir."/";
    $LogFile = $Path.$LogDate."_Viana-BackupMailer.log";

    function WriteLog($LogText){
        $Handle = fopen($GLOBALS['LogFile'], (file_exists($GLOBALS['LogFile'])) ? 'a' : 'w');
        fwrite($Handle, "                                   Viana-BackupMailer Log File                                  \n");
        fwrite($Handle, "================================================================================================\n");
        fclose($Handle);
        file_put_contents($GLOBALS['LogFile'], $LogText, FILE_APPEND | LOCK_EX);
    }

    $DB_BackupFile = ($DB_Name == "" ? "all_databases" : $DB_Name)."_$BackupDate.sql.gz";
    $CMD = "mysqldump -u $DB_Username -h $DB_Server --password='$DB_Password' ".($DB_Name == "" ? "--all-databases" : $DB_Name)." | gzip > ".$Path.$DB_BackupFile;
    passthru($CMD);
    $LogText = date("[Y/m/d H:i:s] (").$DB_BackupFile.") Backup file was CREATED.";
    WriteLog($LogText);

    $Mail_Subject = "[$SiteName] Database Backup";
    $Mail_Message = "\nYour database backup detail : \n";
    $Mail_Message .= "----------------------------------------------------------\n";
    $Mail_Message .= "You Site Name : $SiteName\n";
    $Mail_Message .= "Your Site Title : $SiteTitle\n";
    $Mail_Message .= "Your Database Name : ".($DB_Name == "" ? "All Databases" : $DB_Name)."\n";
    $Mail_Message .= "Your Backup File : $DB_BackupFile\n";
    $Mail_Message .= "----------------------------------------------------------\n";
    $Mail_Message .= "Powered by Yousef Rahimy Akhondzadeh\n\n";
    $AttachFile = $Path.$DB_BackupFile;

    $AttachContent = file_get_contents($AttachFile);
    $AttachContent = chunk_split(base64_encode($AttachContent));
    $Separator = md5(time());
    $EOL = "\r\n";

    $MailHeader = "From: $Mail_From".$EOL;
    $MailHeader .= "MIME-Version: 1.0".$EOL;
    $MailHeader .= "Content-Type: multipart/mixed; boundary=\"".$Separator."\"".$EOL;
    $MailHeader .= "Content-Transfer-Encoding: 7bit".$EOL;
    $MailHeader .= "This is a MIME encoded message.".$EOL;

    $MainBody = "--".$Separator.$EOL;
    $MainBody .= "Content-Type: text/plain; charset=\"iso-8859-1\"".$EOL;
    $MainBody .= "Content-Transfer-Encoding: 8bit".$EOL;
    $MainBody .= $Mail_Message.$EOL;
    $MainBody .= "--".$Separator.$EOL;
    $MainBody .= "Content-Type: application/octet-stream; name=\"".$DB_BackupFile."\"".$EOL;
    $MainBody .= "Content-Transfer-Encoding: base64".$EOL;
    $MainBody .= "Content-Disposition: attachment".$EOL;
    $MainBody .= $AttachContent.$EOL;
    $MainBody .= "--".$Separator."--";

    if (mail($Mail_To, $Mail_Subject, $MainBody, $MailHeader)){
        if ($DeleteBackup) {
            unlink($Path.$DB_BackupFile);
            $LogText = date("[Y/m/d H:i:s] (").$DB_BackupFile.") Backup file was REMOVED from disk.\n";
            WriteLog($LogText);
        }
        $LogText = date("[Y/m/d H:i:s] (").$DB_BackupFile.") Backup file was SENT to email.\n";
        WriteLog($LogText);
    } 
    else{
        $LogText = date("[Y/m/d H:i:s]")."Error on sending email.\n";
        WriteLog($LogText);
        $LogText = date("[Y/m/d H:i:s]").error_get_last()."\n";
        WriteLog($LogText);
    }
?>

请帮助我。 谢谢

能否分享Viana-BackupMailer中的代码? 执行不出来大概有两个原因(都是有权限的):

  1. 访问权限 - you/cron 所有者

  2. 无权执行此 php 文件
  3. 执行此 php 文件的用户无权访问文件夹 /Viana-BackupMailer/ 或在其中创建文件/或 运行 mysqldump 命令