我有一个脚本可以从数据库中进行备份:
<?php
backup_tables('localhost','uname','pass','dbname');
/* backup the db OR just a table */
function backup_tables($host,$user,$pass,$name,$tables = '*')
{
$link = mysql_connect($host,$user,$pass);
mysql_select_db($name,$link);
//get all of the tables
if($tables == '*')
{
$tables = array();
$result = mysql_query('SHOW TABLES');
while($row = mysql_fetch_row($result))
{
$tables[] = $row[0];
}
}
else
{
$tables = is_array($tables) ? $tables : explode(',',$tables);
}
//cycle through
foreach($tables as $table)
{
$result = mysql_query('SELECT * FROM '.$table);
$num_fields = mysql_num_fields($result);
$return.= 'DROP TABLE '.$table.';';
$row2 = mysql_fetch_row(mysql_query('SHOW CREATE TABLE '.$table));
$return.= "\n\n".$row2[1].";\n\n";
for ($i = 0; $i < $num_fields; $i++)
{
while($row = mysql_fetch_row($result))
{
$return.= 'INSERT INTO '.$table.' VALUES(';
for($j=0; $j < $num_fields; $j++)
{
$row[$j] = addslashes($row[$j]);
$row[$j] = ereg_replace("\n","\\n",$row[$j]);
if (isset($row[$j])) { $return.= '"'.$row[$j].'"' ; } else { $return.= '""'; }
if ($j < ($num_fields-1)) { $return.= ','; }
}
$return.= ");\n";
}
}
$return.="\n\n\n";
}
//save file
$handle = fopen('db-backup-'.date("d_h-i").'.sql','w+');
fwrite($handle,$return);
fclose($handle);
}
?>
并且,它每小时使用cron创建一个新备份(例如“ db-backup-31_03-01.sql”) 可以,一切都很好
但是我需要附加要压缩的备份文件并将其发送到我的电子邮件中。 因此,我只需要一个单独的脚本即可从上一个sql文件创建一个zip并附加到电子邮件。
我发现了一些用于发送电子邮件的脚本(like this),但是我不知道如何在发送之前压缩附件?
或者我该如何使用第一个脚本创建压缩备份文件?
答案 0 :(得分:0)
以下是一些来自https://davidwalsh.name/create-zip-php ...
的代码/* creates a compressed zip file */
function create_zip($files = array(),$destination = '',$overwrite = false) {
//if the zip file already exists and overwrite is false, return false
if(file_exists($destination) && !$overwrite) { return false; }
//vars
$valid_files = array();
//if files were passed in...
if(is_array($files)) {
//cycle through each file
foreach($files as $file) {
//make sure the file exists
if(file_exists($file)) {
$valid_files[] = $file;
}
}
}
//if we have good files...
if(count($valid_files)) {
//create the archive
$zip = new ZipArchive();
if($zip->open($destination,$overwrite ? ZIPARCHIVE::OVERWRITE : ZIPARCHIVE::CREATE) !== true) {
return false;
}
//add the files
foreach($valid_files as $file) {
$zip->addFile($file,$file);
}
//debug
//echo 'The zip archive contains ',$zip->numFiles,' files with a status of ',$zip->status;
//close the zip -- done!
$zip->close();
//check to make sure the file exists
return file_exists($destination);
}
else
{
return false;
}
}
在您的情况下,您可以这样使用它:
$files_to_zip = array(
'db-backup-31_03-01.sql'
);
//if true, good; if false, zip creation failed
$result = create_zip($files_to_zip,'db_backup.zip');
在尝试将压缩文件附加到电子邮件之前,请确保检查$result
为TRUE。