|
|
|
Datenbankbackup
Zurück zur Übersicht Diese Script erstellen ein Backup von einer Datenbank bzw. Tabellen.
Es ist sinnvoll, seine Datenbank regelmäßig zu sichern, um einen möglichen Datenverlust vorzubeugen.
Dies kann man entweder per phpMyAdmin machen, was aber zu Zeitaufwendig ist.
Mit diesen Script kann man mit einem Aufruf, verschiedene Datenbank oder Tabellen sichern.
Das Script speichert dann das MySQL-Dump (Backup) entweder auf dem Server, oder sendet dieses als Anhang an eine Email Adresse.
Diesen Script kann man auch per Cronjob z.B. täglich aufrufen lassen.
Sicherung von ganzen Datenbanken
Dieser Script sichert alle Tabellen einer oder mehrerer Datenbanken:
| PHP |
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:
36:
37:
38:
39:
40:
41:
42:
43:
44:
45:
46:
47:
48:
49:
50:
51:
52:
53:
54:
55:
56:
57:
58:
59:
60:
61:
62:
63:
64:
65:
66:
67:
68:
69:
70:
71:
72:
73:
74:
75:
76:
77:
78:
79:
80:
81:
82:
83:
84:
85:
86:
87:
88:
89:
90:
91:
92:
93:
94:
95:
96:
97:
98:
99:
100:
101:
102:
103:
104:
105:
106:
107:
108:
109:
110:
111:
112:
113:
114:
115:
116:
117:
118:
119:
120:
121:
122:
123:
124:
125:
126:
127:
128:
129:
130:
131:
132:
133:
134:
135:
136:
137:
138:
139:
140:
141:
142:
143:
144:
145:
146:
147:
148:
149:
150:
151:
152:
153:
154:
155:
156:
157:
158:
159:
160:
161:
162:
163:
164:
165:
166:
167:
168:
169:
170:
171:
172:
173:
174:
175:
176:
177:
178:
179:
180:
181:
182:
183:
184:
185:
186:
187:
188:
189:
190:
191:
192:
193:
194:
195:
196:
197:
198:
199:
200:
201:
202:
203:
204:
205:
206:
207:
208:
209:
210:
211:
212:
213:
214:
215:
216:
217:
218:
219:
220:
221:
222:
223:
224:
225:
226:
227:
228:
229:
|
<?php
@set_time_limit(0);
//Verbindung zur Datenbank
$verbindung = mysql_connect("localhost","User","Passwort") or die("Username/Passwort falsch");
// MySQL Datenbanken
$dbname = array();
$dbname[]= "datenbank1";
$dbname[]= "datenbank2";
// 0: Normale Datei
// 1: GZip-Datei
$compression = 1;
//Falls Gzip nicht vorhanden, kein Gzip
if(!extension_loaded("zlib"))
$compression = 0;
// Pfad zur aktuellen Datei
$path = ereg_replace ("\\\\","/",__FILE__);
$path = dirname ($path);
$path = trim($path);
// Pfad zum Backup
$path .= "/backup/";
//Speicherart
//0: Nur Server speichern
//1: Zusätzlich per Email versenden
$send = 0;
//Email-Adresse für Backup
$email = "email@adresse";
//Dateityp
if ($compression==1) $filetype = "sql.gz";
else $filetype = "sql";
//Dateieigenschaften
$cur_time=date("d.m.Y H:i");
$cur_date=date("Y-m-d");
//Pfade zu den neuen Backup-Dateien (fur den Mailversand)
//__Nicht verändern___
$backup_pfad = array();
//Erstelle Struktur von Datenbank
function get_def($dbname, $table) {
global $verbindung;
$def = "";
$def .= "CREATE TABLE $table (\n";
$result = mysql_db_query($dbname, "SHOW FIELDS FROM $table",$verbindung);
while($row = mysql_fetch_array($result)) {
$def .= " $row[Field] $row[Type]";
if ($row["Default"] != "") $def .= " DEFAULT '$row[Default]'";
if ($row["Null"] != "YES") $def .= " NOT NULL";
if ($row[Extra] != "") $def .= " $row[Extra]";
$def .= ",\n";
}
$def = ereg_replace(",\n$","", $def);
$result = mysql_db_query($dbname, "SHOW KEYS FROM $table",$verbindung);
while($row = mysql_fetch_array($result)) {
$kname=$row[Key_name];
if(($kname != "PRIMARY") && ($row[Non_unique] == 0)) $kname="UNIQUE|$kname";
if(!isset($index[$kname])) $index[$kname] = array();
$index[$kname][] = $row[Column_name];
}
while(list($x, $columns) = @each($index)) {
$def .= ",\n";
if($x == "PRIMARY") $def .= " PRIMARY KEY (" . implode($columns, ", ") . ")";
else if (substr($x,0,6) == "UNIQUE") $def .= " UNIQUE ".substr($x,7)." (" . implode($columns, ", ") . ")";
else $def .= " KEY $x (" . implode($columns, ", ") . ")";
}
$def .= "\n);";
return (stripslashes($def));
}
//Erstelle Eintäge von Tabelle
function get_content($dbname, $table) {
global $verbindung;
$content="";
$result = mysql_db_query($dbname, "SELECT * FROM $table",$verbindung);
while($row = mysql_fetch_row($result)) {
$insert = "INSERT INTO $table VALUES (";
for($j=0; $j<mysql_num_fields($result);$j++) {
if(!isset($row[$j])) $insert .= "NULL,";
else if($row[$j] != "") $insert .= "'".addslashes($row[$j])."',";
else $insert .= "'',";
}
$insert = ereg_replace(",$","",$insert);
$insert .= ");\n";
$content .= $insert;
}
return $content;
}
//Funktion um Backup auf dem Server zu speichern
function write_backup($val,$newfile,$newfile_data)
{
global $compression,$path,$cur_date,$filetype,$backup_pfad;
$backup_pfad[] = $path.$val."_structur_".$cur_date.".".$filetype;
$backup_pfad[] = $path.$val."_data_".$cur_date.".".$filetype;
if ($compression==1)
{
$fp = gzopen($path.$val."_structur_".$cur_date.".".$filetype,"w9");
gzwrite ($fp,$newfile);
gzclose ($fp);
$fp = gzopen($path.$val."_data_".$cur_date.".".$filetype,"w9");
gzwrite ($fp,$newfile_data);
gzclose ($fp);
}
else
{
$fp = fopen ($path.$val."_structur_".$cur_date.".".$filetype,"w");
fwrite ($fp,$newfile);
fclose ($fp);
$fp = fopen($path.$val."_data_".$cur_date.".".$filetype,"w");
fwrite ($fp,$newfile_data);
fclose ($fp);
}
}
//Backup per Email verschicken
function mail_att($to, $from, $subject, $message) {
// $to Empfänger
// $from Absender ("email@domain.de" oder "Name <email@domain.de>")
// $subject Betreff
// $message Inhalt der Email
global $backup_pfad; //Die Pfade zu den Dateien
if(is_array($backup_pfad) AND count($backup_pfad) > 0)
{
$mime_boundary = "-----=" . md5(uniqid(rand(), 1));
$header = "From: ".$from."\r\n";
$header.= "MIME-Version: 1.0\r\n";
$header.= "Content-Type: multipart/mixed;\r\n";
$header.= " boundary=\"".$mime_boundary."\"\r\n";
$content = "This is a multi-part message in MIME format.\r\n\r\n";
$content.= "--".$mime_boundary."\r\n";
$content.= "Content-Type: text/plain charset=\"iso-8859-1\"\r\n";
$content.= "Content-Transfer-Encoding: 7bit\r\n\r\n";
$content.= $message."\r\n";
//Dateien anhaengen
foreach($backup_pfad AS $file)
{
$name = basename($file);
$data = chunk_split(base64_encode(implode("", file($file))));
$len = filesize($file);
$content.= "--".$mime_boundary."\r\n";
$content.= "Content-Disposition: attachment;\r\n";
$content.= "\tfilename=\"$name\";\r\n";
$content.= "Content-Length: .$len;\r\n";
$content.= "Content-Type: application/x-gzip; name=\"".$file."\"\r\n";
$content.= "Content-Transfer-Encoding: base64\r\n\r\n";
$content.= $data."\r\n";
}
if(mail($to, $subject, $content, $header)) return true;
else return false;
}
return false;
}
//Backup erstellen
while (list(,$val) = each($dbname))
{
$newfile="# Strukturbackup: $cur_time \r\n# www.php-einfach.de \r\n";
$newfile_data="# Datenbackup: $cur_time \r\n# www.php-einfach.de \r\n";
//backup schreiben
$tables = mysql_list_tables($val,$verbindung);
$num_tables = @mysql_num_rows($tables);
$i = 0;
while($i < $num_tables)
{
$table = mysql_tablename($tables, $i);
$newfile .= "\n# ----------------------------------------------------------\n#\n";
$newfile .= "# structur for Table '$table'\n#\n";
$newfile .= get_def($val,$table);
$newfile .= "\n\n";
$newfile_data .= "\n# ----------------------------------------------------------\n#\n";
$newfile_data .= "#\n# data for table '$table'\n#\n";
$newfile_data .= get_content($val,$table);
$newfile_data .= "\n\n";
$i++;
}
write_backup($val,$newfile,$newfile_data);
} //End: while
//Backup per Email senden
if($send == 1)
{
$text="Datenbank-Backup vom: ".date("d.m.Y H:i")."\n\n\n www.php-einfach.de PHP lernen leicht gemacht";
$from = "backup@server.de";
if(!mail_att($email, $from, "Datenbank-Backup ".date("Y-m-d"), $text))
echo "Es konnte <b>keine</b> Email gesendet werden<br>";
}
echo "<h3>Backup ist fertig</h3>";
?>
|
|
Die verschiedenen Datenbanken sind in dem Array $dbname gespeichert.
Die Variable $send gibt an, ob das Backup zusätzlich noch als Email versendet werden soll.
Was die anderen Variablen bewirken, entnehmt ihr bitte den Komentaren.
Backup von bestimmten Tabellen
Manchmal reicht es aus, wenn man nur bestimmte Tabellen sichern möchte.
Dies ist z.B. dann Sinnvoll, wenn man die Backupfunktion in einem größerem Script, z.B. in einem Forum, einbauen möchte. Dort sichert man dann nur die Tabellen des Forum:
| PHP |
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:
36:
37:
38:
39:
40:
41:
42:
43:
44:
45:
46:
47:
48:
49:
50:
51:
52:
53:
54:
55:
56:
57:
58:
59:
60:
61:
62:
63:
64:
65:
66:
67:
68:
69:
70:
71:
72:
73:
74:
75:
76:
77:
78:
79:
80:
81:
82:
83:
84:
85:
86:
87:
88:
89:
90:
91:
92:
93:
94:
95:
96:
97:
98:
99:
100:
101:
102:
103:
104:
105:
106:
107:
108:
109:
110:
111:
112:
113:
114:
115:
116:
117:
118:
119:
120:
121:
122:
123:
124:
125:
126:
127:
128:
129:
130:
131:
132:
133:
134:
135:
136:
137:
138:
139:
140:
141:
142:
143:
144:
145:
146:
147:
148:
149:
150:
151:
152:
153:
154:
155:
156:
157:
158:
159:
160:
161:
162:
163:
164:
165:
166:
167:
168:
169:
170:
171:
172:
173:
174:
175:
176:
177:
178:
179:
180:
181:
182:
183:
184:
185:
186:
187:
188:
189:
190:
191:
192:
193:
194:
195:
196:
197:
198:
199:
200:
201:
202:
203:
204:
205:
206:
207:
208:
209:
210:
211:
212:
213:
214:
215:
216:
217:
218:
219:
220:
221:
222:
223:
224:
225:
226:
227:
228:
229:
230:
231:
232:
233:
234:
235:
236:
237:
238:
239:
240:
241:
242:
243:
244:
245:
246:
247:
248:
249:
250:
251:
252:
253:
254:
255:
256:
257:
258:
259:
260:
261:
262:
263:
264:
265:
266:
267:
268:
269:
|
<?php
@set_time_limit(0);
//Verbindung zur Datenbank
$verbindung = mysql_connect("localhost","User","Passwort") or die("Username/Passwort falsch");
mysql_select_db("datenbankname");
// MySQL Tabellennamen
$tbname = array();
$tbname[]= "tabelle1";
$tbname[]= "tabelle2";
// 0: Normale Datei
// 1: GZip-Datei
$compression = 1;
//Struktur mitspeichern?
//0: Nein
//1: Ja
$struktur = 1;
//Falls Gzip nicht vorhanden, kein Gzip
if(!extension_loaded("zlib"))
$compression = 0;
// Pfad zur aktuellen Datei
$path = ereg_replace ("\\\\","/",__FILE__);
$path = dirname ($path);
$path = trim($path);
// Pfad zum Backup
$path .= "/backup/";
//Speicherart
//0: Auf dem Server speichern
//1: Per Email versenden
//2: Zum Download anbieten
$send = 2;
//Email-Adresse für Backup
$email = "email@adresse";
//Dateityp
if ($compression==1) $filetype = "sql.gz";
else $filetype = "sql";
//Dateieigenschaften
$cur_time=date("d.m.Y H:i");
$cur_date=date("Y-m-d");
//Pfade zu den neuen Backup-Dateien (fur den Mailversand)
//__Nicht verändern___
$backup_pfad = array();
//Erstelle Eintäge von Tabelle
function get_content($table) {
$content="";
$result = mysql_query("SELECT * FROM $table") OR $content = "# $table nicht vorhanden\n #".mysql_error();
while($row = @mysql_fetch_row($result)) {
$insert = "INSERT INTO $table VALUES (";
for($j=0; $j<mysql_num_fields($result);$j++) {
if(!isset($row[$j])) $insert .= "NULL,";
else if($row[$j] != "") $insert .= "'".addslashes($row[$j])."',";
else $insert .= "'',";
}
$insert = ereg_replace(",$","",$insert);
$insert .= ");\n";
$content .= $insert;
}
return $content;
}
//Erstelle Struktur von Datenbank
function get_def($table) {
$def = "";
$def .= "CREATE TABLE $table (\n";
$result = mysql_query("SHOW FIELDS FROM $table");
while($row = @mysql_fetch_array($result)) {
$def .= " `$row[Field]` $row[Type]";
if ($row["Default"] != "") $def .= " DEFAULT '$row[Default]'";
if ($row["Null"] != "YES") $def .= " NOT NULL";
if ($row[Extra] != "") $def .= " $row[Extra]";
$def .= ",\n";
}
$def = ereg_replace(",\n$","", $def);
$result = mysql_query("SHOW KEYS FROM $table");
while($row = @mysql_fetch_array($result)) {
$kname=$row[Key_name];
if(($kname != "PRIMARY") && ($row[Non_unique] == 0)) $kname="UNIQUE|$kname";
if(!isset($index[$kname])) $index[$kname] = array();
$index[$kname][] = $row[Column_name];
}
if(is_array($index)) {
while(list($x, $columns) = each($index)) {
$def .= ",\n";
if($x == "PRIMARY") $def .= " PRIMARY KEY (" . implode($columns, ", ") . ")";
else if (substr($x,0,6) == "UNIQUE") $def .= " UNIQUE ".substr($x,7)." (" . implode($columns, ", ") . ")";
else $def .= " KEY $x (" . implode($columns, ", ") . ")";
}
}
$def .= "\n);";
return (stripslashes($def));
}
//Funktion um Backup auf dem Server zu speichern
function write_backup($data)
{
global $path,$cur_date,$compression,$filetype;
$pfad = $path.$cur_date."_backup.".$filetype;
if ($compression==1)
{
$fp = gzopen($pfad,"w9");
gzwrite ($fp,$data);
gzclose ($fp);
}
else
{
$fp = fopen ($pfad,"w");
fwrite ($fp,$data);
fclose ($fp);
}
echo "<h3>Backup ist fertig</h3>";
}
//Backup per Email verschicken
function mail_att($to, $from, $subject, $message, $data)
{
// $to Empfänger
// $from Absender ("email@domain.de" oder "Name <email@domain.de>")
// $subject Betreff
// $message Inhalt der Email
global $compression,$filetype;
if($compression == 1)
{
$data = @gzencode($data);
$app = "application/x-gzip";
}
else
$app = "text/plain";
$name = date("d-m-Y")."_backup.".$filetype;
$mime_boundary = "-----=" . md5(uniqid(rand(), 1));
$header = "From: ".$from."\r\n";
$header.= "MIME-Version: 1.0\r\n";
$header.= "Content-Type: multipart/mixed;\r\n";
$header.= " boundary=\"".$mime_boundary."\"\r\n";
$content = "This is a multi-part message in MIME format.\r\n\r\n";
$content.= "--".$mime_boundary."\r\n";
$content.= "Content-Type: text/plain charset=\"iso-8859-1\"\r\n";
$content.= "Content-Transfer-Encoding: 7bit\r\n\r\n";
$content.= $message."\r\n";
$data = chunk_split(base64_encode($data));
$len = strlen($data);
$content.= "--".$mime_boundary."\r\n";
$content.= "Content-Disposition: attachment;\r\n";
$content.= "\tfilename=\"$name\";\r\n";
$content.= "Content-Length: .$len;\r\n";
$content.= "Content-Type: ".$app."; name=\"".$name."\"\r\n";
$content.= "Content-Transfer-Encoding: base64\r\n\r\n";
$content.= $data."\r\n";
if(mail($to, $subject, $content, $header))
echo "<h3>Backup wurde per Email versendet</h3>";
else
echo "<h3>Backup konnte _nicht_ gesendet werden</h3>";
}
//Backup als Download anbieten
function download($output)
{
global $compression,$filetype;
if($compression == 1)
{
$ausgabe = @gzencode($output);
if($ausgabe == false)
{
$ausgabe = $output;
$compression = 0;
}
}
else
$ausgabe = $output;
$filename = date("d-m-y")."_backup";
if($compression == 1)
$app = "application/x-gzip";
else
$app = "application/octetstream";
ob_start();
header("Cache-control: private");
header("Content-disposition: filename={$filename}.{$filetype}");
header("Content-type: $app");
header("Pragma: no-cache");
header("Expires: 0");
echo $ausgabe;
ob_end_flush();
}
//Backup erstellen
$tabellen = implode("\n#",$tbname);
$output = "############################
# $cur_time: $datum
# Tabellen: $tabellen
# Datenbankbackup
############################
";
if($struktur == 1)
{
foreach($tbname AS $table)
{
$output .= "\n# ----------------------------------------------------------\n#\n";
$output .= "# Structur for Table '$table'\n#\n";
$output .= get_def($table);
$output .= "\n\n";
}
}
$output .= "\n\n\n\n\n";
foreach($tbname AS $table)
{
$output .= "\n# ----------------------------------------------------------\n#\n";
$output .= "# Data for Table '$table'\n#\n";
$output .= get_content($table);
$output .= "\n\n";
}
//Backup speichern&versenden
$text="Datenbank-Backup vom: ".date("d.m.Y H:i")."\n\n\n www.php-einfach.de PHP lernen leicht gemacht";
$from = "backup@server.de";
switch($send)
{
case 0: write_backup($output); break;
case 1: mail_att($email, $from, "Datenbank-Backup ".date("Y-m-d"), $text, $output); break;
case 2: download($output); break;
default: download($output); break;
}
?>
|
|
Wieder sind hier die Tabellennamen in dem Array $tbname gespeichert.
Desweiteren gibt es hier nur einen dritten Speicherungsmodus.
Und zwar kann das Backup direkt herruntergeladen werden. Dafür muss die Variable $send den Wert 2 enthalten.
Bitte bedenkt, dass der Script je nach Größe der Datenbank einige Sekunden Zeit für die Ausführung benötigt.
Einen Cronjob für das Backup sollte man am besten während der Nacht (zwischen 3 und 4 Uhr) anlegen, denn dann sind die wenigsten Besucher auf eurer Seite.
Sofern euer Server nicht im Safe-Mode läuft, kann eure Datenbank (fast) beliebig groß sein.
Wenn dies nicht der Fall ist, kann es passieren, dass der Script vom PHP-Modul abgebrochen wird, meistens nach 30 Sekunden.
Dafür müssen aber mehrere zehntausend Datensätze in eurer Datenbank vorhanden sein.
Warnung!
Bitte sichert die Script und den Ordner mit einen Passwort.
Nicht das ein Angreifer an das Backup eurer Datenbank gelangt.
Kommentare
Zurück zur Übersicht
Autor Andavos
|
|
|
|