Scripts

Groot backupscript

Dit backupscript heb ik samengesteld uit andere scripts. Wat gebeurt er? 1. Er wordt een .zip bestand aangemaakt, met daarin alle bestanden uit een bepaald map. 2. Er wordt een dump van een MySQL database gemaakt, en deze wordt ook toegevoegd aan het zip-bestand. 3. Het zip bestand wordt als bijlage van een email naar het opgegeven e-mailadres gestuurd. Voor wie is het bedoeld? Dit is voor de wat kleinere websites, dit omdat een email maar maximaal 10mb mag zijn, en je ook te maken hebt met de maximale executie-tijd, je kunt hem natuurlijk altijd aanpassen zodat hij de backup lokaal opslaat (denk wel aan de beveiliging), of upload hem naar een FTP-server. Originele scripts: Zip gehele directory: - http://us2.php.net/manual/en/function.ziparchive-addemptydir.php Dump mysql - http://www.phphulp.nl/php/scripts/3/968/ Email met attachment - http://www.webcheatsheet.com/PHP/send_email_text_html_attachment.php#attachment

groot-backupscript
[code]

<?php


# ******************** #
# ***** SETTINGS ***** #

 
// Enter the dir you want to backup, for example: /var/services/web/diryouwantotbackup.
// Documt Root is default to backup the entire web-root directory.
$dir2backup 		= $_SERVER['DOCUMENT_ROOT'];

// MySQL login data
$db_name="xxxx";
$db_location="localhost";
$db_user="xxxx";
$db_password="xxxx";


// Where to do you want to send the backup to?
$email			="ex#[email protected]";
$subject		="Backup website";

# ***** SETTINGS ***** #
# ******************** #

# ***************************** #
# ***** ZIPPING DIRECTORY ***** #


// Creating random filename for security reasons
$filenamezip = 'BackUp'.rand(1000, 9999).'.zip';

// Creating archive
$zip = new ZipArchive();
$zip->open($filenamezip, ZipArchive::CREATE);

// Setting dir to add to archive
$dirName = $dir2backup;

// Checking dir
if (!is_dir($dirName)) {
    throw new Exception('Directory ' . $dirName . ' does not exist');
}

// Getting realpath
$dirName = realpath($dirName);
if (substr($dirName, -1) != '/') {
    $dirName.= '/';
}



$dirStack = array($dirName);
//Find the index where the last dir starts
$cutFrom = strrpos(substr($dirName, 0, -1), '/')+1;


while (!empty($dirStack)) {
    $currentDir = array_pop($dirStack);
    $filesToAdd = array();

    $dir = dir($currentDir);
    while (false !== ($node = $dir->read())) {
        if (($node == '..') || ($node == '.')) {
            continue;
        }
        if (is_dir($currentDir . $node)) {
            array_push($dirStack, $currentDir . $node . '/');
        }
        if (is_file($currentDir . $node)) {
            $filesToAdd[] = $node;
        }
    }

    $localDir = substr($currentDir, $cutFrom);
    $zip->addEmptyDir($localDir);
   
    foreach ($filesToAdd as $file) {
        $zip->addFile($currentDir . $file, $localDir . $file);
    }
}






# ***** ZIPPING DIRECTORY ***** #
# ***************************** #
 
# ************************* #
# ***** DUMPING MYSQL ***** #


// Connect to mysql database

$connect = mysql_connect($db_location,$db_user,$db_password);
if($connect == TRUE) {
  if(mysql_select_db($db_name) != TRUE) {
    exit("<span style='color: red'>Can't connect to the MySQL database. </body></html>");
  }
}else{
    exit("<span style='color: red'>Can't connect to the MySQL server.</body></html>");
}
   

// return all available tables 
$result_tbl = mysql_query( "SHOW TABLES FROM `$db_name`"); 

// Creating $output.
$output = ''; 
while ($row = mysql_fetch_row($result_tbl)) { // De tabellen  aanmaken
    // Table name
    $table = $row[0];
    // Tabel create
    $output .= "\n\n\tCREATE TABLE ".$table." (\n"; 
    // Select fields
    $result_fld = mysql_query( "SHOW FIELDS FROM ".$table); 
    $aant = mysql_num_rows($result_fld);
    // Start counter
    $i = 0;   
    while($row1 = mysql_fetch_row($result_fld)) {
        // Count ++
        $i++;
        // Fieldname - type - auto_increment
        $output .= "\t\t".$row1[0]." ".$row1[1]." ".$row1[5];
        if($aant != $i){
            // If not last, insert a comma.
            $output .= ",\n";
        }
        // If field = primary key
        if($row1[3] == 'PRI'){
            $output .= "\t\tPRIMARY KEY (".$row1[0].")"; 
            // If not last, insert comma.
            if($aant != $i){
                $output .= ",\n";
            }
        }
    } 
    // Close create table
    $output .= "\n\t);\n\n"; 
    
    // Select data from table
    $insrt_sql = "SELECT * FROM ".$table;
    $insrt_res = mysql_query($insrt_sql);
    while($ins = mysql_fetch_row($insrt_res)){
        // Start INSERT INTO
        $output .= "\tINSERT INTO ".$table." VALUES (";
        for($i=0;$i<count($ins);$i++){
            if(is_numeric($ins[$i])){
                // If nummeric, no quotes
                $output .= $ins[$i];
            }else{                
                // else insert ''
               $output .= "'".str_replace("'","\'",stripslashes($ins[$i]))."'";

            }
            if($i+1<count($ins)){
                // If not last, insert comma
                $output .= ',';
            }
        }
        // close INSERT INTO
        $output .= ");\n";    
    }
} 

 


# ***** DUMPING MYSQL ***** #
# ************************* #

# *************************** #
# ***** FINISHING TOUCH ***** #

// Add MySQL to archive
$zip->addFromString('MySQL DUMP.sql', $output);

// Closing zip file
$zip->close();

# ***** FINISHING TOUCH ***** #
# *************************** #

# *********************************** #
# ***** SENDING BACKUP BY EMAIL ***** #



//create a boundary string. It must be unique
//so we use the MD5 algorithm to generate a random hash
$random_hash = md5(date('r', time()));
//define the headers we want passed. Note that they are separated with \r\n
$headers = "From: $email \r\nReply-To: $email";
//add boundary string and mime type specification
$headers .= "\r\nContent-Type: multipart/mixed; boundary=\"PHP-mixed-".$random_hash."\"";
//read the atachment file contents into a string,
//encode it with MIME base64,
//and split it into smaller chunks
$attachment = chunk_split(base64_encode(file_get_contents($filenamezip)));
//define the body of the message.
ob_start(); //Turn on output buffering
?>
--PHP-mixed-<?php echo $random_hash; ?> 
Content-Type: multipart/alternative; boundary="PHP-alt-<?php echo $random_hash; ?>"

--PHP-alt-<?php echo $random_hash; ?> 
Content-Type: text/plain; charset="iso-8859-1"
Content-Transfer-Encoding: 7bit

Backup of your website created succesfully!
Created on: <? echo date('c'); ?>


--PHP-alt-<?php echo $random_hash; ?> 
Content-Type: text/html; charset="iso-8859-1"
Content-Transfer-Encoding: 7bit

<h2>Backup of your website created succesfully!</h2>
<p>created on <b><? echo date('c'); ?></b></p>

--PHP-alt-<?php echo $random_hash; ?>--

--PHP-mixed-<?php echo $random_hash; ?> 
Content-Type: application/zip; name="backup.zip" 
Content-Transfer-Encoding: base64 
Content-Disposition: attachment 

<?php echo $attachment; ?>
--PHP-mixed-<?php echo $random_hash; ?>--

<?php
//copy current buffer contents into $message variable and delete current output buffer
$message = ob_get_clean(); 
//send the email
$mail_sent = mail($email, $subject, $message, $headers );
//if the message is sent successfully print "Mail sent". Otherwise print "Mail failed"
echo $mail_sent ? "Backup succesfully sent" : "Mail failed"; 

# ***** SENDING BACKUP BY EMAIL ***** #
# *********************************** #

# ************************************** #
# ***** DELETE ARCHIVE FROM SERVER ***** #

unlink($filenamezip);

# ***** DELETE ARCHIVE FROM SERVER ***** #
# ************************************** #

?>
[/code]

Reacties

0
Nog geen reacties.