Sauvegarde d'un site web et de sa base de données et envoi par email

Sauvegarde d'un site web et de sa base de données et envoi par email - PHP - Programmation

Marsh Posté le 19-02-2011 à 14:32:06    

Bonjour,
 
Voici un script php pour exécuter en php la sauvegarde zip de votre site et d'une base de données (séparément). Les sauvegardes sont envoyées par email.
 
Pensez à éditer les premières lignes du script! C'est basé sur la version 4.0.6 de Swift mailer. A mettre dans un sous répertoire /lib
 
Entre autres,
Vous devez indiquer la taille des morceaux de sauvegarde qui sont envoyés dans les emails. Sachant que Googlemail a une limite à 9 Mo pour les pièces attachées.
Vous pouvez utiliser le SSL pour l'envoi de l'email si nécessaire.
Vous avez la possibilité de conserver l'archive .zip sur le site ou de l'effacer.
Vous pouvez le lancer en automatique avec cron.
 
J'espère que ça vous sera aussi utile qu'à moi.
 

Code :
  1. #!/bin/php
  2. <?php
  3. /* Backup a whole website and one database */
  4. // General settings:
  5. $to = '@gmail.com';           // Where to send the emails?
  6. $zippath = '/home/domaine/public_html/backup/filesender/tmp';  // Path to temporarily save backup file - Select an empty directory
  7. $piecesize = 9 * 1024 * 1024;            // In Megabyte - Gmail doesn't allow attachments more than 10 MB.
  8. // Domain settings:
  9. $backupsite = 'yes';      // Want to backup your site? 'yes' or 'no'
  10. $sitepath = '/home/domaine/public_html'; // Which directory to backup? Don't add trailing slash
  11. $zipfile = 'domaineZIP';      // backup file name - not too long name (DON'T INCLUDE ZIP EXTENTION, GMAIL MAY DELETE IT IF EXE INSIDE)
  12. $deletezipsite = 'no';      // Do you want to delete the zip file in the tmp directory after sending emails? 'yes' or 'no'
  13. // Database settings:
  14. $backupdb = 'yes';     // Want to backup a database? 'yes' or 'no'
  15. $dbhost = 'localhost';    // Server address of your MySQL Server
  16. $dbuser = 'domaine_dbuser';  // Username to access MySQL database
  17. $dbpass = '****';  // Password to access MySQL database
  18. $dbname = 'domaine_DB';  // Database Name
  19. $deletezipdb = 'no';    // Do you want to delete the zip file in the tmp directory after sending emails? 'yes' or 'no'
  20. // Sender email account settings:
  21. $from = '@backup.domaine.info';    // Who should the emails be sent from?
  22. $mailserver = 'box.domaine.com';       // SMTP server address
  23. $mailport = '465';            // SMTP server port address
  24. $mailencryption = 'ssl';          // SMTP server encryption protocol
  25. $smtpuser = '@domaine.info';    // SMTP server username
  26. $smtpass = '*****';          // SMTP server password
  27. // ******************************
  28. // Do not Modify below this line!
  29. // ******************************
  30. echo "FileSender.php script started on " . date("l j F Y" ) . " - " . date("G:i:s" ) . br();
  31. echo " ".br();
  32. // Create the tmp directory
  33. if(!file_exists($zippath)) {
  34.  if(mkdir($zippath)) {
  35.   echo "Created target folder $zippath".br();
  36.  }
  37. }
  38. // Delete any previous file from tmp directory
  39. exec("rm -r -f $zippath/*" );
  40. require_once 'lib/swift_required.php';
  41. // Backup the site
  42. if ($backupsite == "yes" ) {
  43. $zipname = $zippath . "/" . $zipfile . ".zip";
  44. echo "Backup of the site just started $sitepath".br();
  45. echo " ".br();
  46. echo "Zipping directory: $sitepath".br();
  47. passthru("nice -n 16 zip -q -r $zipname $sitepath " );
  48. if (file_exists($zipname)==false){
  49. exit ("<h4><center><font color=\"#FF0000\">Server failed to zip $sitepath! <br><br>Hint: Make sure $zippath directory is CHOMD 777 and $sitepath path exists.<br>Quiting... :( </font></center></h4>" ) ;
  50. }
  51. $EstimateSplittedFiles = intval(exec("zipsplit -t -n $piecesize -b $zippath $zipname" ));
  52. if ($EstimateSplittedFiles<=0){
  53. exit ("<h4><center><font color=\"#FF0000\">Server failed to split zip file $zipname! <br>Try to increase desired spilt size in \$piecesize variable.<br>Quiting... :( </center></h4>" ) ;
  54. }
  55. echo "Estimated number of splitted files: " . $EstimateSplittedFiles .br();
  56. echo "Splitting $zipname into $piecesize Mb files ".br();
  57. exec("nice -n 16 zipsplit -n $piecesize -b $zippath $zipname" );
  58. $i = 1;
  59. while (file_exists($zippath . "/" . $zipfile . FormatFileNumber($i) . ".zip" )) {
  60.     rename("$zippath/$zipfile" . FormatFileNumber($i) . ".zip", "$zippath/$zipfile" . FormatFileNumber($i));
  61.     $tmpFileName = "$zippath/$zipfile" . FormatFileNumber($i);
  62.     echo "Processing: $tmpFileName". br();
  63.      
  64.     // Swift mail
  65.     $senddate = date("l j F Y" );
  66.     $mailsubject = "WEB Backup - $senddate - " . date("G:i:s" ) . " - Part " . FormatFileNumber($i) . " / " . $EstimateSplittedFiles ; // Subject in the email to be sent
  67.     $mailbody = "Your web directory backup is attached to this email"; // Brief Message
  68.     $transport = Swift_SmtpTransport::newInstance()
  69.      ->setHost($mailserver)
  70.      ->setPort($mailport)
  71.      ->setEncryption($mailencryption)
  72.      ->setUsername($smtpuser)
  73.      ->setPassword($smtpass);
  74.     $mailer = Swift_Mailer::newInstance($transport);
  75.     $message = Swift_Message::newInstance($mailsubject)
  76.      ->setFrom($from)
  77.      ->setTo($to)
  78.      ->setBody($mailbody);
  79.     $attachment = Swift_Attachment::fromPath($tmpFileName, 'application/zip');
  80.     $message->attach($attachment);
  81.     $result = $mailer->send($message);
  82.    
  83.     echo "Just Sent: $tmpFileName".br();
  84.     exec("rm -r -f $tmpFileName" );
  85.     sleep(7);
  86.     $i++;
  87.     flush;
  88. }
  89.  
  90. if ($deletezipsite == "yes" ) {
  91.  echo " ".br();
  92.  echo "$zipname deleted".br();  
  93.  exec("rm -r -f $zipname" );
  94.  }
  95. echo " ".br();
  96. echo "Finished to send all emails of the backup.".br();  
  97. }
  98. // Backup the database
  99. if ($backupdb == "yes" ) {
  100. echo " ".br();
  101. echo " ".br();
  102. echo "Backup of the database $dbname just started".br();
  103. echo " ".br();
  104. $zipdbname = $zippath . "/" . $dbname . ".zip";
  105. echo "Zipping database: $dbname".br();
  106. passthru("mysqldump --host=$dbhost --user=$dbuser --password=$dbpass $dbname | gzip -c > $zipdbname" );
  107. $buffer = 1024;
  108. $current = 0;
  109. $splitnum = 1;
  110.  
  111. echo "Estimated number of splitted files: " . ceil(filesize($zipdbname)/$piecesize) .br();
  112. if(!$handle = fopen($zipdbname, "rb" )) {
  113.  exit("Unable to open $zipdbname for read! Make sure you edited filesender.php correctly!".br());
  114. }
  115.  
  116. $base_filename = basename($zipdbname);
  117. $piece_name = $zippath.'/'.$base_filename.'.'.str_pad($splitnum, 3, "0", STR_PAD_LEFT);
  118.  
  119. if(!$fw = fopen($piece_name,"w" )) {
  120.  exit("Unable to open $piece_name for write. Make sure target folder is writeable.".br());
  121. }
  122.  
  123. echo "Splitting $base_filename into $piecesize Mb files ".br();
  124. echo "Writing $piece_name".br();
  125. while (!feof($handle) and $splitnum < 999) {
  126.  if($current < $piecesize) {
  127.   if($content = fread($handle, $buffer)) {
  128.    if(fwrite($fw, $content)) {
  129.     $current += $buffer;
  130.     } else {
  131.      exit("filesender.php is unable to write to target folder. Target folder may not have write permission! Try chmod +w target_folder".br());
  132.     }
  133.    }
  134.   } else {
  135.    fclose($fw);
  136.    // Swift mail
  137.    $senddate = date("l j F Y" );
  138.    $mailsubject = "Database Backup - $senddate - " . date("G:i:s" ) . " - Part " . FormatFileNumber($splitnum) .  " / " . ceil(filesize($zipdbname)/$piecesize) ; // Subject in the email to be sent
  139.    $mailbody = "Your database backup is attached to this email"; // Brief Message
  140.    $transport = Swift_SmtpTransport::newInstance()
  141.     ->setHost($mailserver)
  142.     ->setPort($mailport)
  143.     ->setEncryption($mailencryption)
  144.     ->setUsername($smtpuser)
  145.     ->setPassword($smtpass);
  146.    $mailer = Swift_Mailer::newInstance($transport);
  147.    $message = Swift_Message::newInstance($mailsubject)
  148.     ->setFrom($from)
  149.     ->setTo($to)
  150.     ->setBody($mailbody);
  151.    $attachment = Swift_Attachment::fromPath($piece_name, 'application/zip');
  152.    $message->attach($attachment);
  153.    $result = $mailer->send($message);
  154.    echo "Just Sent: $piece_name".br();
  155.    exec("rm -r -f $piece_name" );
  156.    sleep(7);
  157.    $current = 0;
  158.    $splitnum++;
  159.    $piece_name = $zippath.'/'.$base_filename.'.'.str_pad($splitnum, 3, "0", STR_PAD_LEFT);
  160.    echo "Writing $piece_name".br();
  161.    $fw = fopen($piece_name,"w" );
  162.     }
  163.   }
  164. fclose($fw);
  165. // Swift mail
  166. $senddate = date("l j F Y" );
  167. $mailsubject = "Database Backup - $senddate - " . date("G:i:s" ) . " - Part " . FormatFileNumber($splitnum) .  " / " . ceil(filesize($zipdbname)/$piecesize) ; // Subject in the email to be sent
  168. $mailbody = "Your database backup is attached to this email"; // Brief Message
  169. $transport = Swift_SmtpTransport::newInstance()
  170.  ->setHost($mailserver)
  171.  ->setPort($mailport)
  172.  ->setEncryption($mailencryption)
  173.  ->setUsername($smtpuser)
  174.  ->setPassword($smtpass);
  175. $mailer = Swift_Mailer::newInstance($transport);
  176. $message = Swift_Message::newInstance($mailsubject)
  177.  ->setFrom($from)
  178.  ->setTo($to)
  179.  ->setBody($mailbody);
  180. $attachment = Swift_Attachment::fromPath($piece_name, 'application/zip');
  181. $message->attach($attachment);
  182. $result = $mailer->send($message);
  183. echo "Just Sent: $piece_name".br();
  184. exec("rm -r -f $piece_name" );
  185. sleep(7);
  186.  
  187. fclose($handle);
  188.  
  189. if ($deletezipdb == "yes" ) {
  190.  exec("rm -r -f $zipdbname" );
  191.  echo " ".br();
  192.  echo "$zipdbname deleted".br();
  193. }
  194. echo " ".br();
  195. echo "Finished to send all emails of the database.".br();  
  196. exit;
  197. }
  198. // Functions  
  199. function FormatFileNumber($num)
  200. { global $EstimateSplittedFiles;
  201. return sprintf("%0" . strlen($EstimateSplittedFiles) . "d", $num);
  202. }
  203. function br()
  204. { return (!empty($_SERVER['SERVER_SOFTWARE']))?'<br>':"\n";
  205. }
  206. ?>


Message édité par syrinx75 le 06-03-2011 à 09:11:36
Reply

Marsh Posté le 19-02-2011 à 14:32:06   

Reply

Sujets relatifs:

Leave a Replay

Make sure you enter the(*)required information where indicate.HTML code is not allowed