Sunday, January 28, 2018

database backup using php

<?php
error_reporting(E_ALL);
ini_set('display_errors', '1');    // 0 or 1 set 1 if unable to download database it will show all possible errors
ini_set('max_execution_time', 0);  // setting 0 for no time limit
session_start();
define('BACKUP_DIR', './myBackups' ) ;

// to import database dump
if(isset($_POST['upload'])){
   
$filename = BACKUP_DIR.DIRECTORY_SEPARATOR.trim($_POST['dbName']);
$dbHost = 'localhost';
$dbUser = 'root';
$dbPass = '';
$dbName = 'school1';

// Define  Database Credentials
define('HOST', $dbHost ) ;
define('USER', $dbUser ) ;
define('PASSWORD', $dbPass ) ;
define('DB_NAME', $dbName ) ;

$maxRuntime = 8; // less then your max script execution limit


$deadline = time()+$maxRuntime;
$progressFilename = $filename.'_filepointer'; // tmp file for progress
$errorFilename = $filename.'_error'; // tmp file for erro


$mysqli = new mysqli(HOST , USER , PASSWORD , DB_NAME) ;
if (mysqli_connect_errno())
{
   printf("Connect failed: %s", mysqli_connect_error());
   exit();
}
/*mysql_connect($dbHost, $dbUser, $dbPass) OR die('connecting to host: '.$dbHost.' failed: '.mysql_error());
mysql_select_db($dbName) OR die('select db: '.$dbName.' failed: '.mysql_error());*/

($fp = fopen($filename, 'r')) OR die('failed to open file:'.$filename);

// check for previous error
if( file_exists($errorFilename) ){
    die('<pre> previous error: '.file_get_contents($errorFilename));
}

// activate automatic reload in browser
echo '<html><head> <meta http-equiv="refresh" content="'.($maxRuntime+2).'"><pre>';

// go to previous file position
$filePosition = 0;
if( file_exists($progressFilename) ){
    $filePosition = file_get_contents($progressFilename);
    fseek($fp, $filePosition);
}

$queryCount = 0;
$query = '';
while( $deadline>time() AND ($line=fgets($fp, 1024000)) ){
    if(substr($line,0,2)=='--' OR trim($line)=='' ){
        continue;
    }

    $query .= $line;
    if( substr(trim($query),-1)==';' ){
        //if( !mysql_query($query) ){
        if( !$mysqli->query($query) ){
            $error = 'Error performing query \'<strong>' . $query . '\': ' . mysql_error();
            file_put_contents($errorFilename, $error."\n");
            exit;
        }
        $query = '';
        file_put_contents($progressFilename, ftell($fp)); // save the current file position for
        $queryCount++;
    }
}

if( feof($fp) ){
    echo 'dump successfully restored!';
}else{
    echo ftell($fp).'/'.filesize($filename).' '.(round(ftell($fp)/filesize($filename), 2)*100).'%'."\n";
    echo $queryCount.' queries processed! please reload or wait for automatic browser refresh!';
}

}

// to delete file
if(isset($_GET['task'])&& $_GET['task']=='clear'){
    $file_name=$_GET['file'];
    $file=BACKUP_DIR.DIRECTORY_SEPARATOR.$file_name;
    if(file_exists($file)){ if(unlink($file)) $rmsg="$file_name Deleted successfully";}
    else { $rmsg="<b>$file_name </b>Not found already removed";}
}

// to dump database
if(isset($_REQUEST['submit'])){
#####################
//CONFIGURATIONS 
#####################
// Define the name of the backup directory
$backupType=trim($_POST['db_type']);
if($backupType=='hmis'){
    $host='localhost';
    $user='root';
    $password='';
    $database='gautam';
} else {
    $host='localhost';
    $user='root';
    $password='';
    $database='school';
}
//if(!empty($host)&&!empty($user)&&!empty($password)&&!empty($database))
// Define  Database Credentials
define('HOST', $host ) ;
define('USER', $user ) ;
define('PASSWORD', $password ) ;
define('DB_NAME', $database ) ;
/*
Define the filename for the sql file
If you plan to upload the  file to Amazon's S3 service , use only lower-case letters
*/
$dataset='3';
$fileName = $database.'.sql' ;
//$fileName = 'mysqlbackup--' . date('d-m-Y') . '@'.date('h.i.s').'.sql' ;
// Set execution time limit
if(function_exists('max_execution_time')) {
if( ini_get('max_execution_time') > 0 ) set_time_limit(0) ;
}

// Check if directory is already created and has the proper permissions
if (!file_exists(BACKUP_DIR)) mkdir(BACKUP_DIR , 0700) ;
if (!is_writable(BACKUP_DIR)) chmod(BACKUP_DIR , 0700) ;

// Create an ".htaccess" file , it will restrict direct accss to the backup-directory .
$content = 'Allow from all' ;
$file = new SplFileObject(BACKUP_DIR . '/.htaccess', "w") ;
$file->fwrite($content) ;

$mysqli = new mysqli(HOST , USER , PASSWORD , DB_NAME) ;
if (mysqli_connect_errno())
{
   printf("Connect failed: %s", mysqli_connect_error());
   exit();
}
 // Introduction information
$return='';
 $return .= "--\n";
$return .= "-- A Mysql Backup System \n";
$return .= "--\n";
$return .= '-- Export created: ' . date("Y/m/d") . ' on ' . date("h:i") . "\n\n\n";
$return = "--\n";
$return .= "-- Database : " . DB_NAME . "\n";
$return .= "--\n";
$return .= "-- --------------------------------------------------\n";
$return .= "-- ---------------------------------------------------\n";
$return .= 'SET AUTOCOMMIT = 0 ;' ."\n" ;
$return .= 'SET FOREIGN_KEY_CHECKS=0 ;' ."\n" ;
$tables = array() ;
// Exploring what tables this database has
$result = $mysqli->query('SHOW TABLES' ) ;
// Cycle through "$result" and put content into an array
while ($row = $result->fetch_row())
{
    $tables[] = $row[0] ;
}
// Cycle through each  table
foreach($tables as $table)
{
    // Get content of each table
    $result = $mysqli->query('SELECT * FROM '. $table) ;
    // Get number of fields (columns) of each table
    $num_fields = $mysqli->field_count  ;
    // Add table information
    $return .= "--\n" ;
    $return .= '-- Tabel structure for table `' . $table . '`' . "\n" ;
    $return .= "--\n" ;
    $return.= 'DROP TABLE  IF EXISTS `'.$table.'`;' . "\n" ;
    // Get the table-shema
    $shema = $mysqli->query('SHOW CREATE TABLE '.$table) ;
    // Extract table shema
    $tableshema = $shema->fetch_row() ;
    // Append table-shema into code
    $return.= $tableshema[1].";" . "\n\n" ;
    // Cycle through each table-row
    $totalRows=$result->num_rows;
    if($totalRows>0){
        $return .= 'INSERT INTO `'.$table .'` VALUES' ;
        $count=0;
        while($rowdata = $result->fetch_row())
        {
            $return1='';
            // Prepare code that will insert data into table
            $return1 .= ' (';
            // Extract data of each row
            for($i=0; $i<$num_fields; $i++)
            { 
            $return1 .= '"'.$mysqli->real_escape_string($rowdata[$i]) . "\"," ;
            }
            // Let's remove the last comma
            $return1 = substr("$return1", 0, -1) ;
            $return1 .= ")";
            $val[]=$return1;
            $count++;
            if($count%$dataset=='0'){
                $return2=implode(',', $val);
                unset($val);
                $return.=$return2.";\n";
                if($count<$totalRows){
                    $return .= 'INSERT INTO `'.$table .'` VALUES' ;
                }               
            }
        }
        if(isset($val) && count($val)>0){
            $return2=implode(',', $val);
            unset($val);
            $return.=$return2.";\n";
        }       
    }
 $return .= "\n\n" ;
}
// Close the connection
$mysqli->close() ;
$return .= 'SET FOREIGN_KEY_CHECKS = 1 ; '  . "\n" ;
$return .= 'COMMIT ; '  . "\n" ;
$return .= 'SET AUTOCOMMIT = 1 ; ' . "\n"  ;
//$file = file_put_contents($fileName , $return) ;

$handle = fopen(BACKUP_DIR . '/' .$fileName, 'w+');
fwrite($handle, $return);
fclose($handle);

// for zip save
/*$zip = new ZipArchive() ;
$resOpen = $zip->open(BACKUP_DIR . '/' .$fileName.".zip" , ZIPARCHIVE::CREATE) ;
if( $resOpen ){
    $zip->addFromString( $fileName , "$return" ) ;
}
$zip->close() ;
$fileSize = get_file_size_unit(filesize(BACKUP_DIR . "/". $fileName . '.zip')) ; */
// Function to append proper Unit after file-size .
}

?>
<div class="backup_main">
    <div class="main">
                    <div class="overlay"><div class="overlay-load"><div class="overlay-msg">
                      Please wait database backup is being generated. It may take a few minute depending on database size, please do not refresh or close the browser window.       
                </div></div></div>
        <fieldset><legend><h2>Database Backup</h2></legend>
            <form name="backup" id="backup" method="post">
                <div><label>HMIS Database :</label><input type="radio" name="db_type" value="hmis" checked="checked" /></div>
                <div class="cls"></div>
                <div><label>HERP Database :</label><input type="radio" name="db_type" value="herp" /></div>
                <div class="cls"></div>
                <div style="text-align: center;margin-top: 50px"><input onclick="vky(this)" type="submit" id="getdb" name="submit" value="Get database" /></div>
                <div class="cls"></div>
            </form>
        </fieldset>
    </div>
    <script type="text/javascript">
    function vky(x){
        x.value='Wait processing..';
        document.getElementsByClassName("overlay")[0].style.display="block";
    }
    </script>
    <div class="backup_list">
        <div class=""><?php echo isset($rmsg)?$rmsg:''; ?></div>
        <?php echo display_download(BACKUP_DIR); ?>
    </div> 
</div>

<style type="text/css">
/* HTML5 display-role reset for older browsers */
html, body, div, span, applet, object, iframe,h1, h2, h3, h4, h5, h6, p, blockquote, pre,a,fieldset, form, label, legend,table, caption, tbody, tfoot, thead, tr, th, td{margin: 0;padding: 0;border: 0;font-size: 100%;font: inherit;vertical-align: baseline;}
body {line-height: 1;}
ol, ul {list-style: none;}
blockquote:before, blockquote:after,table { border-collapse: collapse;border-spacing: 0;}
fieldset legend{margin-left: 20px;}
fieldset legend h2{}
form{margin: 25px;}
.cls{clear:both;border-bottom: 0px;padding: 0px}
form div{border-bottom: dotted 1px #ccc;padding: 15px;}
h2{font-size: 14px;font-weight: bold}
.backup_main{font-size: 12px;font-family: verdana;width:1040px;margin:auto}
.backup_list{ background: #f9f9f9;width:500px;min-height: 410px;height: auto; padding: 10px;float:left }
.main{ position:relative; background: #f9f9f9;width:500px;height: auto; padding: 10px;font-size: 12px;font-family: verdana;float:left }
fieldset{border:solid 1px #ccc;}
div > label{font-weight: bold;width:150px;display: inline-block}
input[type="submit"]{width: 150px;cursor: pointer;height: 35px;font-size: 14px;border: 1px #ccc solid; -moz-transition: all 0.5s ease-out; -o-transition: all 0.5s ease-out; -webkit-transition: all 0.5s ease-out; -ms-transition: all 0.5s ease-out; }
input[type="submit"]:hover{ background: #000; color:#fff }
table{width:500px;margin-bottom: 100px;border: solid 1px #ccc;border-collapse: collapse}
table > thead > tr > th {ext-align: left;border-bottom: 1px #ccc solid;border-right: 1px #ccc solid;}
table > tbody > tr > td {ext-align: left;border-bottom: 1px #ccc solid;border-right: 1px #ccc solid;height: 20px;line-height: 20px;padding:5px}
table > tbody > tr > td img:hover {width:14px;height: 14px; -moz-transition: all 0.5s ease-out; -o-transition: all 0.5s ease-out; -webkit-transition: all 0.5s ease-out; -ms-transition: all 0.5s ease-out; }
a.tooltips {  position: relative;  display: inline;}
a.tooltips span {position: absolute;width:140px;color: #000000;background: #FFFFFF;border: 2px solid #CCCCCC;height: 32px;line-height: 32px;text-align: center;visibility: hidden;border-radius: 6px;box-shadow: 0px 0px 7px #808080;}
a.tooltips span:before {content: '';position: absolute;top: 100%;left: 50%;margin-left: -12px;width: 0; height: 0;border-top: 12px solid #CCCCCC;border-right: 12px solid transparent;border-left: 12px solid transparent;}
a.tooltips span:after {content: '';position: absolute;top: 100%;left: 50%;margin-left: -8px;width: 0; height: 0;border-top: 8px solid #FFFFFF;border-right: 8px solid transparent;border-left: 8px solid transparent;}
a:hover.tooltips span {visibility: visible;opacity: 1;bottom: 30px;left: 50%;margin-left: -76px;z-index: 999;}
.logout{text-align: right;width:100%;height: 25px;background: #1A1111;line-height: 25px;}
.logout a{color:#fff;margin-right: 50px;}
/*.overlay{position: absolute;width:100%;height: 100%;background: red;opacity: .50;top:0px;left: 0px;display: none;}*/
.overlay {display: none;position: absolute;width: 100%;height: 100%;top: 0px;left: 0px;background: #ccc;z-index: 1001;opacity: .95;}
.overlay-load {width: 350px;height: 100px;margin: auto;top: 0px;bottom: 0px;position: absolute;left: 0px;right: 0px;
           border: solid 1px #060522;text-align: center;
           background: #fff  50% 25%;
background-repeat: no-repeat;         
}
.overlay-msg{margin-bottom: 10px;bottom: 0px;position: absolute;font-style: italic;color: rgb(19, 19, 19);}           
</style>
<?php
function get_file_size_unit($file_size){
switch (true) {
    case ($file_size/1024 < 1) :
        return intval($file_size ) ." Bytes" ;
        break;
    case ($file_size/1024 >= 1 && $file_size/(1024*1024) < 1)  :
        return intval($file_size/1024) ." KB" ;
        break;
default:
return intval($file_size/(1024*1024)) ." MB" ;
}
}
function display_download($BACKUP_DIR){
$msg='';
$msg.='<h2>BACKUP  completed ,</h2>
 <table><thead><tr><th>File</th><th>Size</th><th>&nbsp;</th></tr>
</thead><tbody>';
$downloads=getDownloads($BACKUP_DIR);
if(count($downloads)>0)
foreach ($downloads as $k => $v) {
$msg.= '<tr><td>'.$v['name'].'</td><td>'.$v['size'].'</td><td>
<a class="tooltips" href="'.BACKUP_DIR . "/". $v['name'] .'" target="_blank"><span>Click to download</span><img src="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAA8AAAAPCAYAAAA71pVKAAAAtElEQVR42mNgQAMGBgb+xsbGH42MjP7BMJC/X09PT4yBEAAq9Abi/+gYaIjPqGYokJGR4QRKbgIqOgykr+DQfBUkD8RbgJgLxQBDQ8NYoIIv2DQiGfAFqC4OqwuAcZwAVPANh8ZvQJyI18/AxOCLQ7MvNtus0YQYoQZ8h2r8DnSqH0gcW+h+wOYCfX39RKBtd0A0jlj5j1MzEVEK1vwRaHo6CfqYgN7IBGsGOm0uvujBE20NAHg8npa1TPgkAAAAAElFTkSuQmCC"/></a>
&nbsp;|&nbsp;<a onclick="return confirm(\'Are you sure want to remove this file ?\')" class="tooltips" href="mysql_backup.php?task=clear&file='.$v['name'].'"><span>Click to Remove</span><img src="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAA8AAAAPCAYAAAA71pVKAAAAp0lEQVR42rWSWwoDIQxFXUUX0H+V6B6m/3YJ3eY8dtMNTH9mSh/3QoSBQnUsFS4xISfRqBGRSwjhCj1rFGO8w/beezEEEXjtFbjRaLUW+NEMUx8wZjDhPgnxWTvM9Bkvwkw0WLAn+Cut+qkIa6eOgHPuoGCXT/IVVq0ZpEXOUnVn+LfmzhjMeQMsuRD26b/T3vXO/Ku//LC+ER44GOGGlWo7Mt9ae3wDSJ1BX+TxzPsAAAAASUVORK5CYII="/></a>
<form method="post" action="" name="updateform" ><input type="hidden" name="dbName" value="'.$v['name'].'">
<input type="submit" name="upload" value="upload">
</form>
</td></tr>';


}
return $msg.='</tbody></table>';
}
function getDownloads($dir="./myBackups"){
    if (is_dir($dir)){
    $dh  = opendir($dir);
    $files=array();
    $i=0;
    $xclude=array('.','..','.htaccess');
    while (false !== ($filename = readdir($dh))) {
       if(!in_array($filename, $xclude))
       {
        $files[$i]['name'] = $filename;
        $files[$i]['size'] = get_file_size_unit(filesize($dir.'/'.$filename));
        $i++;
       }
    }
    return $files;
}}?>

No comments:

Post a Comment