Ver Mensaje Individual
  #4 (permalink)  
Antiguo 27/03/2016, 01:35
Avatar de a2garrido
a2garrido
 
Fecha de Ingreso: diciembre-2013
Mensajes: 6
Antigüedad: 10 años, 4 meses
Puntos: 2
Respuesta: BACKUP Y RESTORE de MYSQL (muy bueno)

Restaurar.php (corrige problemas de acentos y añade gestion SQL complementaria a PhpMyAdmin):
1ª PARTE
Código PHP:
<?php
header
("Content-Type: text/html;charset=utf-8");
setlocale(LC_ALL'es_ES');

error_reporting(E_ALL E_NOTICE);
ini_set('upload_max_filesize''80M');
ini_set('post_max_size''80M');
ini_set('memory_limit''-1'); //evita el error Fatal error: Allowed memory size of X bytes exhausted (tried to allocate Y bytes)...
ini_set('max_execution_time'300); // es lo mismo que set_time_limit(300) ;
ini_set('mysql.connect_timeout'300);
ini_set('default_socket_timeout'300);
// En MYSQL archivo "my.ini" o "my.cnf" ==> max_allowed_packet = 22M
//"SET GLOBAL max_allowed_packet = 22M;"
//"SET GLOBAL net_read_timeout=50;"
//esto no se si solo es modificable en php.ini:
ini_set('file_uploads','On'); 
ini_set('upload_tmp_dir','upload');
set_time_limit(300); //alarga el timeout


    
$host=empty($_POST["host"])? "localhost":$_POST["host"];  //valor predeterminado 
$usuario=empty($_POST["usuario"])? "root":$_POST["usuario"]; //valor predeterminado
$passwd= empty($_POST["passwd"])? "gtjclm":$_POST["passwd"]; //valor predeterminado
$BD$_POST["BD"];    

function 
convertir_utf8$cadena ) { 
    if ( 
strlen(utf8_decode($cadena)) == strlen($cadena) ) {           
                
// $cadena is not UTF-8            
        
return iconv("ISO-8859-1""UTF-8//TRANSLIT"$cadena);
    } else {    
// already UTF-8
        
return $cadena;
    }
    
// Alternativa0 $strSQLs = mb_convert_encoding($strSQLs, 'HTML-ENTITIES', "UTF-8");
    // Alternativa1 $strSQLs = iconv('ISO-8859-1','UTF-8//TRANSLIT',$strSQLs);
    // Alternativa2 $strSQLs = mb_convert_encoding($strSQLs, 'UTF-8',  mb_detect_encoding($strSQLs, 'UTF-8, ISO-8859-1', true));
}
                
function 
Debug($Texto,$variable,$crear=false){
   if (
$gestor fopen("log.txt", ($crear)?'w':'a')){ 
           
$t microtime(true);
        
$micro sprintf("%06d",($t floor($t)) * 1000000);
          
fwrite($gestordate("Y-m-d H:i:s.").$micro ."==***==== $Texto ===***===\r\n".print_r($variable,true)."\r\n") ;
         
fclose($gestor); 
   } else die(
"NO SE PUEDE CREAR log.txt");
}
function 
CadenaAcotada($Cadena,$CadenaInicio,$CadenaFinal){
    
$inicio=stripos(" ".$Cadena,$CadenaInicio);//ponemos un espacio para distinguir entre no encontrado o estar al prinicipio
    
if ($inicio) {
        
$inicio += strlen($CadenaInicio)-1;
        
$fin=stripos($Cadena,$CadenaFinal,$inicio);
        if (!
$fin) return false;
        return 
substr($Cadena,$inicio,$fin-$inicio);
    }else  return 
false;
}
function 
TableToHTML($conexion,$strSQL){
    
//$conexion  viene de hacer $conexion = new mysqli(...);
    //$strSQL es el SQL que retorna tegistos p.ej. SELECT
    
$rs $conexion->query$strSQL )or die("No se puede ejecutar la consulta: $strSQL MySQL: \n".$conexion->error);
    
$num_rows$rs->num_rows;
    if ( 
$num_rows <> 0) {
            
$regSELECT$rs->fetch_assoc();
            
$strHTML '<table border="1" cellpadding="10" cellspacing="1" > <thead> <tr>';
            
$x=0;
            foreach (
$regSELECT as $key=>$value) {
                
$strHTML .= "<th><b>".$key."</b></th>";
            }     
            
$strHTML .= "</tr> </thead> <tbody>";
            do {
                
$strHTML .= "<tr>";
                
$x=0;
                foreach (
$regSELECT as $value) {
                    
$strHTML .= "<td > ".$value." </td>";                                
                }
                
$strHTML .= "</tr>";
            } While  (
$regSELECT$rs->fetch_assoc());
            
$strHTML .= " </tbody> </table>";
            return 
nl2br($strHTML);
    }
    return 
"Sin registros en resultado";
}

function 
run_sql($strSQLs,$BD$host$usuario,$passwd$DropDataBase,$InsertDatos,$VerSoloErrores,$tblName){
    
$lines=explode("\n",$strSQLs);
    
$strSQLs = array();
    
$in_comment false;
    foreach (
$lines as $key => $line){
        
$line=trim($line); //preg_replace("#.*/#","",$line)
        
$ignoralinea=(( "#" == $line[0] ) || ("--" == substr($line,0,2)) || (!$line) || ($line==""));
        if (!
$ignoralinea){
            
//Eliminar comentarios que empiezan por /* y terminan por */    
            
if( preg_match("/^\/\*/", ($line)) )       $in_comment true;
            if( !
$in_comment )     $strSQLs[] = $line ;
            if( 
preg_match("/\*\//", ($line)) )      $in_comment false;
        }
    }
    unset(
$lines);
    
// Particionar en sentencias
    
$IncludeDelimiter=false;
    
$delimiter=";";
    
$delimiterLen1;
    
$sql="";
    
// CONEXION 
    
$conexion = new mysqli($host$usuario$passwd) or die ("No se puede conectar con el servidor MySQL: %s\n"$conexion->connect_error);
    if (
$conexion->connect_errno) {
        
printf("No se puede conectar con el servidor MySQL: %s\n"$conexion->connect_error);
        exit();
    }
    if (!
$conexion->set_charset("utf8")) {  // cambiar el conjunto de caracteres a utf8 
        
printf("Error cargando el conjunto de caracteres utf8: %s\n"$conexion->error);
        exit();
    }
    if (
$DropDataBase) {
        
$respuesta $conexion->query("DROP DATABASE ".$BD);
    }
     
    
$NumLin=0;
    foreach (
$strSQLs as $key => $line){
        if (
"DELIMITER" == substr($line,0,9)){  //empieza por DELIMITER
            
$D=explode(" ",$line);
            
$delimiter$D[1];
            
$delimiterLenstrlen($delimiter);
            
$sql=($IncludeDelimiter)? $line ."\n" "";
        }elseif (
substr($line,-1*$delimiterLen) == $delimiter) { //hemos alcanzado el  Delimiter
                
if (($NumLinea++ % 100)==0) {// ver con que base de datos estamos para poder reconectar caso de error
                        
                        
$respuesta $conexion->query("select database() as db");
                        
$row $respuesta->fetch_array(MYSQLI_NUM);
                        
$db=$row[0];
                }
                
$sql .= ($IncludeDelimiter)? $line substr($line,0,-1*$delimiterLen);
                
$sqlInsert = (("INSERT"==substr($sql,0,6)) || ("COMMIT"==substr($sql,0,6))) ;
                if ((
$InsertDatos && $sqlInsert ) || !$sqlInsert){
                    if (!empty(
$tblName)) {
                    
/* restaurar solo una tabla o una vista --> sólo ejecutar las lineas que empiecen por USE,    DROP TABLE, CREATE TABLE, 
                    INSERT IGNORE,    DROP VIEW,    CREATE VIEW, Create trigger
                    */
                    
if ("USE" == strtoupper(substr($sql,0,3))){
                        
$db =substr($sql,5,strlen($sql)-7);
                        
$RunSQL true;
                    } elseif (
"CREATE DATABASE" == strtoupper(substr($sql,0,15))){
                        
$RunSQL true;
                    } else {
                        
$Instruccion=strtoupper(substr($sql,0,10));
                        
$TrozoTXT=explode("`",$sql);
                        switch (
$Instruccion){
                            case 
"DROP TABLE":
                            case 
"CREATE TAB":
                            case 
"DROP VIEW ":
                            case 
"CREATE VIE":
                                
// $tablePos = 3;
                                // break;
                            
case "DROP TRIGG"
                            case 
"INSERT IGN":
                                
$tablePos 1;
                                break;
                            case 
"CREATE TRI":
                                
$tablePos 5;
                        }    
                        if (
$TrozoTXT[$tablePos+1] === "."$tablePos += 2//incluye el nombre de BBDD
                        
$RunSQL= ($tblName == $TrozoTXT[$tablePos]);
                    }    
                } else {
                    
$RunSQL true;
                }
                if (
$RunSQL){
                    
$respuesta $conexion->query($sql);
                    if (
$respuesta){ 
                        if (!
$VerSoloErrores) echo "<br>$NumLinea Ejecutado:  "strtr((strlen($sql)>100)? substr($sql,0,100)."..." $sql, array("\n" => " "));
                    }else {
                            echo 
"<br><b><u>$NumLinea E R R O R: ".$conexion->errno." :</u></b>"$conexion->error ." ====> "substr($sql,0,1022)."...";
                            if (!
$conexion->ping() ){ 
                                
$conexion = new mysqli($host$usuario$passwd) or die ("No se puede RECONECTAR con el servidor MySQL: %s\n"$conexion->connect_error);
                                if (!
$conexion->set_charset("utf8")) {  // cambiar el conjunto de caracteres a utf8 
                                        
printf("Error cargando el conjunto de caracteres utf8: %s\n"$conexion->error);
                                        exit();
                                }
                                
$conexion->select_db($db);
                                
$respuesta $conexion->query($sql);
                                if (
$respuesta) echo "<br>$NumLinea REEJECUTADO:  "strtr(substr($sql,0,130),array("\n" => " ")) . "...";
                                    else echo 
"<br><b><u>$NumLinea REPITE-E R R O R: ".$conexion->errno." :</u></b>"$conexion->error ." ====> "substr($sql,0,1022)."...";
                            }
                        }
                    }
                }
                
$sql="";
        } else { 
//no hemos alcanzado el delimitador el delimitador siempre debe estar al final de linea
                
$sql .= $line ."\n";
        }
    }
    
$conexion->close();    
}
function 
run_split_sql($uploadfile$host$usuario,$passwd,$NewBD,$DropDataBase,$InsertDatos,$VerSoloErrores,$fixUtf8,$tblName){
    
$x =explode("."$uploadfile);
    
$ext end($x);
    switch (
$ext){
        case 
"sql":
            
$strSQLs file_get_contents($uploadfile);
            
unlink($uploadfile);
            break;
        case 
"zip":
            
$zip = new ZipArchive
            
$zip->open($uploadfile); 
            
$zip->extractTo("./"); 
            
$zip->close(); 
            
unlink($uploadfile);//borra el zip
            
$NewFile=stristr($uploadfile,".".$ext,true);//le quitamos la ext
            
$strSQLs file_get_contents($NewFile);
            break;
        case 
"gz":
            
$strSQLs implode(""gzfile($uploadfile));
            break;
        case 
"bz2":
            
$bz bzopen($uploadfile"r") or die("No se pudo abrir el fichero $file para lectura");
            
$decompressed_file '';
            while (!
feof($bz)) {
                
$strSQLs .= bzread($bz4096);
            }
            
bzclose($bz);
            break;
    }