简体   繁体   中英

MySQL daily backups with PHP

I am using Cpanel2 on my webhost, and it has full backup option, but that's not what I need.

I am thinking of some way to make my application make daily backup of database and e-mail me file.

I think I could do that with one PHP page, to do it with login or with running it, but It's not safe and it's similar to Cpanel backup itself.

Is there any way to make my phpmyadmin or cpanel to send me backup of database on mail ?

EDIT: I have tried with system("mysqldump -h $dbhost -u $dbuser -p$dbpass $dbname > $backupfile"); But all I get is 0KB empty file.

Two ways:

1)

    <?php
$db_file_name = $_GET['file_name'];
backup_tables($_GET['host'],$_GET['user'],$_GET['pass'],$_GET['database']);

/* backup the db OR just a table */
function backup_tables($host,$user,$pass,$name,$tables = '*')
{
    global $db_file_name;
  $link = mysql_connect($host,$user,$pass);
  mysql_select_db($name,$link);

  //get all of the tables
  if($tables == '*')
  {
    $tables = array();
    $result = mysql_query('SHOW TABLES');
    while($row = mysql_fetch_row($result))
    {
      $tables[] = $row[0];
    }
  }
  else
  {
    $tables = is_array($tables) ? $tables : explode(',',$tables);
  }

  //cycle through
  foreach($tables as $table)
  {
    $result = mysql_query('SELECT * FROM '.$table);
    $num_fields = mysql_num_fields($result);

    $return.= 'DROP TABLE IF EXISTS '.$table.';';
    $row2 = mysql_fetch_row(mysql_query('SHOW CREATE TABLE '.$table));
    $return.= "\n\n".$row2[1].";\n\n";

    for ($i = 0; $i < $num_fields; $i++) 
    {
      while($row = mysql_fetch_row($result))
      {
        $return.= 'INSERT INTO '.$table.' VALUES(';
        for($j=0; $j<$num_fields; $j++) 
        {
          $row[$j] = addslashes($row[$j]);
          $row[$j] = ereg_replace("\n","\\n",$row[$j]);
          if (isset($row[$j])) { $return.= '"'.$row[$j].'"' ; } else { $return.= '""'; }
          if ($j<($num_fields-1)) { $return.= ','; }
        }
        $return.= ");\n";
      }
    }
    $return.="\n\n\n";
  }  
  //save file
  $handle = fopen($db_file_name.'.sql','w+');
  fwrite($handle,$return);
  fclose($handle);
}

?>

This will save an .sql file in whatever folder you run this from. Then just do a simple php-mailer with this attached, and off you go.

2) I've been using syncsage.com for this and website backups. It's still in beta but so far it's amazing.

Depending on the size of your database, your host may not support sending such a big file. What you need to do is create a cron job (with PHP) or a schedule job in phpMyAdmin that will create a dump of your database. You would then need a script that sends this backup to you.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM