Foros del Web » Programando para Internet » PHP »

hacer backup/restore desde interfaz php

Estas en el tema de hacer backup/restore desde interfaz php en el foro de PHP en Foros del Web. Hola, mi problema tal como el titulo... Estoy haciendo un sistema Web y lo unico que me falta es lograr hacer un respaldo de la ...
  #1 (permalink)  
Antiguo 22/03/2011, 17:10
Avatar de Beuses  
Fecha de Ingreso: marzo-2009
Ubicación: Maracaibo
Mensajes: 132
Antigüedad: 15 años, 1 mes
Puntos: 5
Pregunta hacer backup/restore desde interfaz php

Hola, mi problema tal como el titulo...

Estoy haciendo un sistema Web y lo unico que me falta es lograr hacer un respaldo de la base de datos
desde la interfaz del usuario administrador...

estoy usando postgres como almacenador de los datos de mi sistema..

He buscado muchisimo y me he encontrado con pg_dump, pero me encontre (en los contados lugares donde encontre informmación)
que hace los backup pero sin data..

De verdad necesito ayuda para lograr completar mi sistema :

De antemano gracias...
  #2 (permalink)  
Antiguo 22/03/2011, 17:13
Avatar de mashter  
Fecha de Ingreso: mayo-2008
Mensajes: 116
Antigüedad: 15 años, 11 meses
Puntos: 6
Respuesta: hacer backup/restore desde interfaz php

por medio de pg_dump create ejecuciones en shell, en caso de ser varios comandos podrias create un script

en windows y como opcion independiente a la aplicacion esta cobianbackup
__________________
- - - - - - - - -
  #3 (permalink)  
Antiguo 22/03/2011, 18:00
Avatar de Beuses  
Fecha de Ingreso: marzo-2009
Ubicación: Maracaibo
Mensajes: 132
Antigüedad: 15 años, 1 mes
Puntos: 5
Respuesta: hacer backup/restore desde interfaz php

gracias por responder rapido, pero podrias darme un ejemplo, es que nunca he hecho eso.
  #4 (permalink)  
Antiguo 22/03/2011, 21:13
Avatar de mashter  
Fecha de Ingreso: mayo-2008
Mensajes: 116
Antigüedad: 15 años, 11 meses
Puntos: 6
Respuesta: hacer backup/restore desde interfaz php

con exec ejecutas tu script y este puede ser de 2 modos, aki un ejemplo con mysql

//metodo 1 detiene bases de datos y realiza copia de los archivos
//en otra carpeta, terminando otra vez reinicia el servidor
//rsync solo ara la copia de los archivos modificados

archivo metodo1.sh
#genera respaldo de hoy
/etc/init.d/mysqld stop
rsync -vrplogDtH /var/lib/mysql /respaldo/servidor/mysql/data
/etc/init.d/mysqld start


metodo 2:

Código PHP:
$comando="mysqldump --user=$usuario --password=$pass --databases $mi_bd> /PATH/TO/MI-RESPALDO.SQL";
shell_exec($comando); 


solo acoplalo a la BD que necesites
__________________
- - - - - - - - -
  #5 (permalink)  
Antiguo 23/03/2011, 09:49
Avatar de Beuses  
Fecha de Ingreso: marzo-2009
Ubicación: Maracaibo
Mensajes: 132
Antigüedad: 15 años, 1 mes
Puntos: 5
Respuesta: hacer backup/restore desde interfaz php

Ok, muy bien... como en la web.. puro mysql :/
pero probaré a ver si funciona para lo que necesito y digo como me fue.. :)
  #6 (permalink)  
Antiguo 24/03/2011, 11:45
Avatar de Beuses  
Fecha de Ingreso: marzo-2009
Ubicación: Maracaibo
Mensajes: 132
Antigüedad: 15 años, 1 mes
Puntos: 5
Busqueda Respuesta: hacer backup/restore desde interfaz php

Bien, gracias mashter pero con el codigo que me pasaste...

Código PHP:
$comando="mysqldump --user=$usuario --password=$pass --databases $mi_bd> /PATH/TO/MI-RESPALDO.SQL";
shell_exec($comando); 
no me fue muy bien.. quizas xq hice algo mal...

Código PHP:
<?php
$comando
="pg_dump user=postgres password=123456 databases bd_consejo > /C:/MI-RESPALDO.SQL";
shell_exec($comando);
?>
seguí buscando y encontre este codigo:

Código PHP:
<?php
  $host
=$_COOKIE[host];
  
$usuario=$_COOKIE[usuario];
  
$password=$_COOKIE[password];
  
$nombre_bd=$_COOKIE[nombre_bd];
  
$archivo ="pirulo.bak";
  
$comando =  "pg_dump -U ".$usuario." -d ".$nombre_bd." > ".$archivo;
  print 
"$comando";

 
  
$salida=shell_exec($comando);
  echo 
$salida;
  if (
$salida)
 {
    
$jr_error=error_get_last();
    
cartel("Error tipo: ".$jr_error['type']. " Mensaje: ".$jr_error['message']." Archivo: ".$jr_error['file']. " Linea: ".$jr_error['line']);
  }
?>
esto hace que en mi pagina salga el siguiente mensaje:

Código HTML:
pg_dump -U -d > pirulo.bak
El problema es que no se donde ha guardado el "Respaldo" ese codigo
Si pudieran explicarme donde se supone está... seria muy bueno...
Muchas gracias de antemano nuevamente...
  #7 (permalink)  
Antiguo 24/03/2011, 13:19
Avatar de mashter  
Fecha de Ingreso: mayo-2008
Mensajes: 116
Antigüedad: 15 años, 11 meses
Puntos: 6
Respuesta: hacer backup/restore desde interfaz php

no se estan pasando las variables de usuario y tabla, ademas agregale el pass para ke no lo pida ya ke probablemente no te genero el respaldo y ponle ruta absoluta al archivo de respaldo tipo

/mis/respaldos/pirulo.bak


en un sistema que ando haciendo coloque el respaldo que se ejecute 2 veces al dia por medio de cron; y despues solo are uno para seleccionar el respaldo y restaurar
__________________
- - - - - - - - -
  #8 (permalink)  
Antiguo 24/03/2011, 14:39
Avatar de Beuses  
Fecha de Ingreso: marzo-2009
Ubicación: Maracaibo
Mensajes: 132
Antigüedad: 15 años, 1 mes
Puntos: 5
Busqueda Respuesta: hacer backup/restore desde interfaz php

encontré este codigo en la pagina de Postgresql http://archives.postgresql.org/pgsql...2/msg00023.php
y traté de adaptarlo a mi
BD

Código PHP:
<?php
// scrypt for backup and restore postgres database


function dl_file($file)
{
  if (!
is_file($file)) { die("<b>404 File not found!</b>"); }
  
$len filesize($file);
  
$filename basename($file);
  
$file_extension strtolower(substr(strrchr($filename,"."),1));
  
$ctype="application/force-download";
  
header("Pragma: public");
  
header("Expires: 0");
  
header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
  
header("Cache-Control: public");
  
header("Content-Description: File Transfer");
  
header("Content-Type: $ctype");
  
$header="Content-Disposition: attachment; filename=".$filename.";";
  
header($header );
  
header("Content-Transfer-Encoding: binary");
  
header("Content-Length: ".$len);
  @
readfile($file);
  exit;
}



$action  $_POST["actionButton"];
$ficheiro=$_FILES["path"]["name"];
switch (
$action)
{
   case 
"Import":
     
$dbname "prueba"//database name
     
$dbconn pg_pconnect("host=localhost port=5432 dbname=$dbname user=postgres password=123456"); //connectionstring

     
if (!$dbconn)
     {
       echo 
"Can't connect.\n";
       exit;
     }
     
$back fopen($ficheiro,"r");
     
$contents fread($backfilesize($ficheiro));
     
$res pg_query(utf8_encode($contents));
     echo 
"Upload Ok";
     
fclose($back);
 break;
 case 
"Export":
 
$dbname "prueba"//database name
 
 
$dbconn pg_pconnect("host=localhost port=5432 dbname=$dbname user=postgres password=123456"); //connectionstring

 
if (!$dbconn)
 {
   echo 
"Can't connect.\n";
 exit;
 }
 
$back fopen("$dbname.sql","w");
 
$res pg_query(" select relname as tablename
                   from pg_class where relkind in ('r')
                   and relname not like 'pg_%' and relname not like 'sql_%' order by tablename"
);

 
$str="";
 while(
$row pg_fetch_row($res))
 {
   
$table $row[0];
   
$str .= "\n--\n";
   
$str .= "-- Estrutura da tabela '$table'";
   
$str .= "\n--\n";
   
$str .= "\nDROP TABLE $table CASCADE;";
   
$str .= "\nCREATE TABLE $table (";
   
$res2 pg_query("SELECT attnum,attname , typname , atttypmod-4 , attnotnull ,atthasdef ,adsrc AS def FROM pg_attribute, pg_class, pg_type, pg_attrdef
   WHERE pg_class.oid=attrelid AND pg_type.oid=atttypid AND attnum>0 AND pg_class.oid=adrelid AND adnum=attnum AND atthasdef='t' AND lower(relname)='$table' UNION
   SELECT attnum,attname , typname , atttypmod-4 , attnotnull , atthasdef ,'' AS def FROM pg_attribute, pg_class, pg_type WHERE pg_class.oid=attrelid
   AND pg_type.oid=atttypid AND attnum>0 AND atthasdef='f' AND lower(relname)='$table' "
); while($r pg_fetch_row($res2))

   {
   
$str .= "\n" $r[1]. " " $r[2];
    if (
$r[2]=="varchar")
   {
   
$str .= "(".$r[3] .")";
   }
   if (
$r[4]=="t")
   {
   
$str .= " NOT NULL";
   }
   if (
$r[5]=="t")
   {
   
$str .= " DEFAULT ".$r[6];
   }
   
$str .= ",";
   }

$str=rtrim($str","); $str .= "\n);\n";

   
$str .= "\n--\n";
   
$str .= "-- Creating data for '$table'";
   
$str .= "\n--\n\n";


$res3 pg_query("SELECT * FROM $table");

   while(
$r pg_fetch_row($res3))
   {
     
$sql "INSERT INTO $table VALUES ('";
     
$sql .= utf8_decode(implode("','",$r));
     
$sql .= "');";
     
$str str_replace("''","NULL",$str);

$str .= $sql$str .= "\n";

   }

$res1 pg_query("SELECT pg_index.indisprimary, pg_catalog.pg_get_indexdef(pg_index.indexrelid)
                 FROM pg_catalog.pg_class c, pg_catalog.pg_class c2, pg_catalog.pg_index AS pg_index
                 WHERE c.relname = '$table'
                 AND c.oid = pg_index.indrelid
                 AND pg_index.indexrelid = c2.oid
                 AND pg_index.indisprimary"
);
   while(
$r pg_fetch_row($res1))
   {
   
$str .= "\n\n--\n";
   
$str .= "-- Creating index for '$table'";
   
$str .= "\n--\n\n";
   
$t str_replace("CREATE UNIQUE INDEX"""$r[1]);
   
$t str_replace("USING btree""|"$t);
   
// Next Line Can be improved!!!
   
$t str_replace("ON""|"$t);
   
$Temparray explode("|"$t);

$str .= "ALTER TABLE ONLY "$Temparray[1] . " ADD CONSTRAINT " $Temparray[0] . " PRIMARY KEY " $Temparray[2] .";\n"; } }

 
$res pg_query(" SELECT
 cl.relname AS tabela,ct.conname,
  pg_get_constraintdef(ct.oid)
  FROM pg_catalog.pg_attribute a
  JOIN pg_catalog.pg_class cl ON (a.attrelid = cl.oid AND cl.relkind = 'r')
  JOIN pg_catalog.pg_namespace n ON (n.oid = cl.relnamespace)
  JOIN pg_catalog.pg_constraint ct ON (a.attrelid = ct.conrelid AND
  ct.confrelid != 0 AND ct.conkey[1] = a.attnum)
  JOIN pg_catalog.pg_class clf ON (ct.confrelid = clf.oid AND clf.relkind = 'r')
  JOIN pg_catalog.pg_namespace nf ON (nf.oid = clf.relnamespace)
  JOIN pg_catalog.pg_attribute af ON (af.attrelid = ct.confrelid AND
  af.attnum = ct.confkey[1]) order by cl.relname "
);
 while(
$row pg_fetch_row($res))
 {
   
$str .= "\n\n--\n";
   
$str .= "-- Creating relacionships for '".$row[0]."'";
   
$str .= "\n--\n\n";
   
   
$str .= "ALTER TABLE ONLY ".$row[0] . " ADD CONSTRAINT " $row[1] . " " $row[2] . ";";
   } 
fwrite($back,$str);

 
fclose($back);
 
dl_file("$dbname.sql");
 break;
}
/**/
?>

<html>
<head>
</head>
<body>

<form id="dataForm" name="dataForm" method="post" enctype="multipart/form-data" action="">

   <input type="file" name="path" id="path" style="width:300px"/>

<input type="submit" value="Import" name="actionButton" id="actionButton" > <input type="submit" value="Export" name="actionButton" id="actionButton" >

</form>
</body>
</html>
Peero cuando ejecuto el boton de import me genera este error...

Código HTML:
Warning: fread(): supplied argument is not a valid stream resource in C:\xampp\htdocs\SSST\genera.php on line 73

Warning: pg_query() [function.pg-query]: Query failed: in C:\xampp\htdocs\SSST\genera.php on line 74
Upload Ok
Warning: fclose(): supplied argument is not a valid stream resource in C:\xampp\htdocs\SSST\genera.php on line 76
y este cuando ejecuto el boton export

Código HTML:
Warning: pg_query() [function.pg-query]: Query failed: ERROR: relation "tbl_prueba" does not exist in C:\xampp\htdocs\SSST\genera.php on line 131

Warning: pg_fetch_row() expects parameter 1 to be resource, boolean given in C:\xampp\htdocs\SSST\genera.php on line 133

Warning: Cannot modify header information - headers already sent by (output started at C:\xampp\htdocs\SSST\genera.php:8) in C:\xampp\htdocs\SSST\genera.php on line 43

Warning: Cannot modify header information - headers already sent by (output started at C:\xampp\htdocs\SSST\genera.php:8) in C:\xampp\htdocs\SSST\genera.php on line 44

Warning: Cannot modify header information - headers already sent by (output started at C:\xampp\htdocs\SSST\genera.php:8) in C:\xampp\htdocs\SSST\genera.php on line 45

Warning: Cannot modify header information - headers already sent by (output started at C:\xampp\htdocs\SSST\genera.php:8) in C:\xampp\htdocs\SSST\genera.php on line 46

Warning: Cannot modify header information - headers already sent by (output started at C:\xampp\htdocs\SSST\genera.php:8) in C:\xampp\htdocs\SSST\genera.php on line 47

Warning: Cannot modify header information - headers already sent by (output started at C:\xampp\htdocs\SSST\genera.php:8) in C:\xampp\htdocs\SSST\genera.php on line 48

Warning: Cannot modify header information - headers already sent by (output started at C:\xampp\htdocs\SSST\genera.php:8) in C:\xampp\htdocs\SSST\genera.php on line 50

Warning: Cannot modify header information - headers already sent by (output started at C:\xampp\htdocs\SSST\genera.php:8) in C:\xampp\htdocs\SSST\genera.php on line 51

Warning: Cannot modify header information - headers already sent by (output started at C:\xampp\htdocs\SSST\genera.php:8) in C:\xampp\htdocs\SSST\genera.php on line 52
-- -- Estrutura da tabela 'tbl_prueba' -- DROP TABLE tbl_prueba CASCADE; CREATE TABLE tbl_prueba ( nombre varchar(-5), cedula int4 NOT NULL ); -- -- Creating data for 'tbl_prueba' -- -- -- Creating index for 'tbl_prueba' -- ALTER TABLE ONLY schema_prueba.tbl_prueba ADD CONSTRAINT tbl_prueba_pkey PRIMARY KEY (cedula);
Por Favor!! ayudaa!! siento q estoy tan cerca y a la vez tan lejos..!! :
  #9 (permalink)  
Antiguo 24/03/2011, 15:32
Avatar de mashter  
Fecha de Ingreso: mayo-2008
Mensajes: 116
Antigüedad: 15 años, 11 meses
Puntos: 6
Respuesta: hacer backup/restore desde interfaz php

antes de header no debes de imprimir nada; posiblemente te ayude el comando error_reporting(0);
__________________
- - - - - - - - -

Etiquetas: php+postgres
Atención: Estás leyendo un tema que no tiene actividad desde hace más de 6 MESES, te recomendamos abrir un Nuevo tema en lugar de responder al actual.
Respuesta




La zona horaria es GMT -6. Ahora son las 10:44.