You are not logged in.

wcf.regNote.message

Hexo

Intermediate

  • "Hexo" started this thread

Posts: 297

  • Send private message

1

Friday, September 14th 2007, 10:46pm

Datenbackupscript

Hey.

Ich hab ein wirklich gutes Datenbackupscript gefunden:

Source code

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
<?php
######## einstellungen #############################################

$db_name = "IhreDatenBank";
$db_passwd = "IhrDatenBankPasswort";

$downloadlink_erstellen = "ja";

$bestaetigungsmail_senden = "ja";
$bestaetigungsmail_adresse = "IhreMailAdresse";
$bestaetigungsmail_betreff = "[BACKUP] Ihr Backupscript";

$sql_file = "dump_" . $db_name . "_" . date('Ymd_Hi') . ".sql";

####################################################################

### daten überprüfen
if ( $db_name == "IhreDatenBank" or $db_passwd == "IhrDatenBankPasswort" )
{
die("FEHLER: Sie m&uuml;ssen zun&auml;chst Ihre Datenbankdaten im Script eingeben!");
}
if ( file_exists($sql_file) or file_exists($sql_file . ".gz") )
{
die("FEHLER: Das zu erstellende Dump existiert bereits!");
}

## dump erstellen
exec("mysqldump -u $db_name -p$db_passwd --quick --allow-keywords --add-drop-table --complete-insert --quote-names $db_name >$sql_file");
exec("gzip $sql_file");

### größe ermitteln
$datei = $sql_file . ".gz";
$size = filesize($datei);
$i = 0;
while ( $size > 1024 )
{
$i++;
$size = $size / 1024;
}
$fileSizeNames = array(" Bytes", " KiloBytes", " MegaBytes", " GigaBytes", " TerraBytes");
$size = round($size,2);
$size = str_replace(".", ",", $size);
$groesse = "$size $fileSizeNames[$i]";

### nachricht erstellen
$message = "Ihr Backup der Datenbank <b>" . $db_name . "</b> wurde durchgeführt.<br>";
$message .= "Die Größe des erstellten Dumps beträgt <b>" . $groesse . "</b>.<br>";

if ($downloadlink_erstellen == "yes" or $downloadlink_erstellen == "ja" or $downloadlink_erstellen == "1")
{
$link = 'http://'.$_SERVER['HTTP_HOST'].$_SERVER['PHP_SELF'];
$link = str_replace(basename(__FILE__),$datei,$link);
$message .= "Downloadlink: <a href='" . $link . "'>" . $datei . "</a>";
}

## nachricht ausgeben
echo $message;

### mail versenden
$message = str_replace("<br>", "\r\n", $message);
$message = str_replace("<b>", "", $message);
$message = str_replace("</b>", "", $message);
if ($bestaetigungsmail_senden == "yes" or $bestaetigungsmail_senden == "ja" or $bestaetigungsmail_senden == "1")
{
if(!preg_match( '/^([a-zA-Z0-9])+([.a-zA-Z0-9_-])*@([a-zA-Z0-9_-])+(.[a-zA-Z0-9_-]+)+/' , $bestaetigungsmail_adresse))
{
echo "<br>FEHLER: Mail konnte nicht versendet werden, da die Adresse ung&uuml;ltig ist!";
}
else
{
mail($bestaetigungsmail_adresse, $bestaetigungsmail_betreff,
$message,"From: backupscript@{$_SERVER['SERVER_NAME']}\r\n" . "Reply-To: backupscript@{$_SERVER['SERVER_NAME']}\r\n")
or die("FEHLER: Mail konnte wegen eines unbekannten Fehlers nicht versendet werden");
echo "<br>Best&auml;tigungsmail wurde erfolgreich versandt!";
}
}
?>


Ich hab Probleme mit dem Cronjob und MySqldumper bei All-inkl.de (Pearltimeout) und müsste deswegen auf ne alternative zurückgreifen....

Das Script oben erstellt einfach nur ein Backup, Packt es und speichert es auf dem Webspace.
Kann man das noch so erweitern, das das aktuelle Backup beim versenden der Bestätigungsemail angehangen wird?

Prometheus

Administrator

Posts: 3,278

  • Send private message

2

Tuesday, September 18th 2007, 11:32am

Machbar ist das auf jeden Fall. Ist nur die Frage ob das was bringt. Wenn das Backup 5 GB groß ist dann bist Du den halben Tag am Emails runter laden.

Was das Timeout betrifft da würde ich sagen kannst Du nicht viel machen sofern Du keinen Root Zugriff hast. Den Dump anzulegen dauert eben einen Moment. Du kannst höchstens versuchen ob AllInkl Shell Kommandos erlaubt und dann den Dump damit erzeugen.
Jedwege Anfragen bitte an Technomausi oder ShaoKhan richten. Dieses Konto ist und bleibt inaktiv.

splasch

Beginner

Posts: 24

  • Send private message

3

Wednesday, October 17th 2007, 11:26am

Hmm ich hab mir mal dein Backup script angesehen. Das arbeitet aber mit shell befehlen die direkt am Server ausgeführt werden. Nicht jeder Webspace betreiber erlaubt dir so einen zugriff.

Ich hab damals eines gefunden das löst das eleganter und zwar dierekt über sql abfragen.
Da kann man sich dann mindesten sicher sein das es zuverlässig überall läuft.
Wobei auch dort ständig verbesserungen gemacht werden.

Man kann einstellen wieviel Backups angelegt werden sollen bis das erste Backup wieder überschrieben wird. Und natürlich die Zeit intervalle wann es durch geführt werden soll.

Zusätzlich hab ich mir dann im Admin bereich einen button gemacht wo man ein Backup gleich erstellt wird und zum Download dann erscheint.

Mfg Splasch

Hexo

Intermediate

  • "Hexo" started this thread

Posts: 297

  • Send private message

4

Wednesday, October 17th 2007, 12:22pm

Ich sach mal so, das Script ist eine Vorlage von all-inkl.com
Dein Script hört sich super an. Wo findet man das?

splasch

Beginner

Posts: 24

  • Send private message

5

Wednesday, October 17th 2007, 12:31pm

Wo ich das gefunden habe weiß ich nicht mehr aber ich kann dir den Quellcode hier posten.

Das ganze nennt sich phpmybackup-0.4-beta unter dem solltes im Netz dann auch was finden

Backup code

PHP Source code

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
<?
// mySQL - variables
$dbhost="localhost";
$dbuser="user";
$dbpass="pass";
$dbname="mydb";

// number of backups to keep
$backups 5;

// hours between backups
$interval 12;

// 1 only with ZLib support, else change value to 0
$compression 1;

// full path to phpMyBackup
$path="/home/pages/htdocs/phpmybackup/";



// DO NOT CHANGE THE LINES BELOW

$version "0.4 beta";
flush();
$conn mysql_connect($dbhost,$dbuser,$dbpass) or die(mysql_error());
$path $path "dump/";
if (!is_dir($path)) mkdir($path0777);

function get_def($dbname$table) {
    global $conn;
    $def "";
    $def .= "DROP TABLE IF EXISTS $table;#%%\n";
    $def .= "CREATE TABLE $table (\n";
    $result mysql_db_query($dbname"SHOW FIELDS FROM $table",$conn);
    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",$conn);
     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));
}

function get_content($dbname$table) {
     global $conn;
     $content="";
     $result mysql_db_query($dbname"SELECT * FROM $table",$conn);
     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;
}

if ($compression==1$filetype "sql.gz";
else $filetype "sql";

if (filemtime($path "0.$filetype") < time() - $interval 3600 && !eregi("/restore\.",$PHP_SELF)) {
    for ($i $backups-1$i 0$i--) {
        $oldname $i-".$filetype";
        $newname $i ".$filetype";
        @rename($path.$oldname,$path.$newname);
    }
    
    $cur_time=date("Y-m-d H:i");
    $newfile="# Dump created with 'phpMyBackup v.$version' on $cur_time\r\n";
    $tables mysql_list_tables($dbname,$conn);
    $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($dbname,$table);
       $newfile .= "\n\n";
       $newfile .= "#\n# data for table '$table'\n#\n";
       $newfile .= get_content($dbname,$table);
       $newfile .= "\n\n";
       $i++;
    }
    
    if ($compression==1) {
        $fp gzopen($path."0.$filetype","w9");
        gzwrite ($fp,$newfile);
        gzclose ($fp);
    } else {
        $fp fopen ($path."0.$filetype","w");
        fwrite ($fp,$newfile);
        fclose ($fp);
    }
}
?>


Restore Code also Wiederherstellung der Db

PHP Source code

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
<?
include "backup.php";
?>
<html>
<head>
<title>phpMyBackup v.<? echo $version;?></title>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
<script language="JavaScript">
<!--
function restore(what) {
   if (confirm("Are you sure you want to overwrite the database with the file " + what +  "?")) {
         window.location = "restore.php?file=" + what;
   }
}
//-->
</script>
</head>
<body bgcolor="#FFFFFF" text="#000000">
<table width="100%" border="0" cellpadding="3">
  <tr>
    <td bgcolor="#DDDDDD" align="center"> <b><font face="Verdana, Arial, Helvetica, sans-serif">phpMyBackup 
      v.<? echo $version;?></font></b></td>
  </tr>
</table>
<p align="center"><?
if ($file!="") {
    $filename $file;
    set_time_limit(180);
    if ($compression ==1$file=gzread(gzopen($path.$file"r"), 10485760);
    else $file=fread(fopen($path.$file"r"), 10485760);
    $query=explode(";#%%\n",$file);
    for ($i=0;$i count($query)-1;$i++) {
        mysql_db_query($dbname,$query[$i],$conn) or die(mysql_error());
    }
    echo "<b>$filename successfully restored!</b>";
}
?></p>
<div align="center">
  <table border="0" cellpadding="5">
    <tr align="center"> 
      <td><u><i>File</i></u></td>
      <td><u><i>Size</i></u></td>
      <td><u><i>Date</i></u></td>
    </tr>
    <?
    $dir=opendir($path); 
    while ($file readdir ($dir)) { 
        if ($file != "." && $file != ".." && eregi("\.sql",$file)) { 
            echo "<tr><td>$file&nbsp;</td>
                <td align=\"right\">&nbsp;" bcdiv(filesize($path.$file),1024,1) . " kB&nbsp;</td>
                <td>&nbsp;" date("Y-m-d H:i",filemtime($path.$file)) . "</td>
                <td>&nbsp;<a href=\"javascript:restore('$file')\"><b>Restore</b></a>&nbsp;</td>
                <td>&nbsp;<a href=\"dump/$file\">View/Download</a></td>&nbsp;</tr>"; 
        } 
    }
    closedir($dir);
?>
  </table>
</div>
</body>
</html>


Und zu guter Letzt Backup mit Mail funktion

PHP Source code

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
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
<?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&uuml;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:

<?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&uuml;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 0write_backup($output); break; 
   case 1mail_att($email$from"Datenbank-Backup ".date("Y-m-d"), $text$output); break; 
   case 2download($output); break; 
   default: download($output); break; 
   } 
?>


Ich ziehe diese Script der shell methode vor da man selbst auf das Backup geschehen einfluss hat und Teille kommentieren kann in der Backup datei.

Mfg Splasch

This post has been edited 3 times, last edit by "splasch" (Oct 17th 2007, 12:42pm)


Prometheus

Administrator

Posts: 3,278

  • Send private message

6

Wednesday, October 17th 2007, 12:54pm

Von dem Skript gibts inzwischen auch schon irgendwas mit Version 1.x im Netz. Hier mal der Link zur Webseite des Authors.
http://www.normsland.co.uk/phpmybackup/

Ich bin nicht sicher ob der Author erlaubt das sein Code hier gepostet wird aber ich setze voraus das dies vorher abgeklärt wurde.
Jedwege Anfragen bitte an Technomausi oder ShaoKhan richten. Dieses Konto ist und bleibt inaktiv.

splasch

Beginner

Posts: 24

  • Send private message

7

Wednesday, October 17th 2007, 1:11pm

So hab mal rumgesucht vom den Script dürfte es keine neuere Version geben.
Das Projekt wurde schon 2001 eingestellt.

Download ist zu finden unter
http://www.m-tecs.net/index.php?a=products&b=pmb&c=de

Das script ist Freeware und darf uneingeschränk von jedem benutz werden.

Mfg Splasch

This post has been edited 1 times, last edit by "splasch" (Oct 17th 2007, 1:11pm)


Prometheus

Administrator

Posts: 3,278

  • Send private message

8

Wednesday, October 17th 2007, 3:40pm

Is das Skript was ich da gefunden hatte denn ein anderes? Ich habs mir nicht genau angeschaut nur der Name hat eben gepasst.

Was das Thema Freeware betrifft kann ich Dir nur raten das Thema mal genauer anzuschauen. Freeware bedeutet nicht das Du es irgendwo selbst anbieten darfst.
[WIKI]freeware[/WIKI]
Jedwege Anfragen bitte an Technomausi oder ShaoKhan richten. Dieses Konto ist und bleibt inaktiv.

wcf.user.socialbookmarks.titel