PHP database backup

Tags: , , ,

I recently added in a way for admin users to download a backup of the database to a CMS I work on.  I came up with something between this solution and this one.  Add this little snippet after a database connection and change “table_1″ and “table_2″ to whichever tables you’d like to output, and add as many tables as you need.

What I like about this script is that it doesn’t save a copy to the server so folks can’t nab it if they know the entire URL, but it can be easily integrated to a web based interface.  It also uses “create table if not exists” which was missing from the other two scripts.  I think a backup should create tables in case you loose the table structure, but it shouldn’t delete the existing data.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
<?php
function datadump ($table) {
    $result .= "# Dump of $table \n";
    $result .= "# Dump DATE : " . date("d-M-Y") ."\n\n";
    
    $row2 = mysql_fetch_row(mysql_query('SHOW CREATE TABLE '.$table));
    $result .= "\n\n".str_replace('CREATE TABLE','CREATE TABLE IF NOT EXISTS',$row2[1]).";\n\n";
    
    $query = mysql_query("select * from $table");
    $num_fields = @mysql_num_fields($query);
    $numrow = mysql_num_rows($query);
    
    for ($i =0; $i<$numrow; $i++) {
        while($row = mysql_fetch_row($query)) {
            $result .= "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])) $result .= "\"$row[$j]\"" ; else $result .= "\"\"";
                if ($j<($num_fields-1)) $result .= ",";
            }
            $result .= ");\n";
        }
    }
    return $result . "\n\n\n";
}
 
$content = datadump('table_1').datadump('table_2');
 
$file_name = "database_backup.sql";
Header("Content-type: application/octet-stream");
Header("Content-Disposition: attachment; filename=$file_name");
echo $content;
?>

Permalink » 3 Comments