Backup Mysql in PHP
1.238 visiteBackup Mysql in PHP
Uno dei task più importanti per un programmatore PHP è fare il backup del proprio database Mysql. Non è raro infatti ricevere attacchi informatici e sperimentare la distruzione della propria fonte di dati rendendo non più fruibile il proprio sito.
Quindi è necessario pensare ad una soluzione che contempli l’ esecuzione automatica e regolare di uno script PHP che permetta di fare copia di backup su file del proprio database.
E’ facile notare come il nostro problema sia composto da tre sotto-problemi:
- Creare una funzione che scrive su file
- Creare una funzione che copia il database
- Temporizzare l’esecuzione del backup mysql in PHP
Funzione che scrive su File in PHP
E’ possibile scrivere su file in PHP utilizzando le funzioni native fopen, fwrite e fclose:
1 2 3 4 5 6 7 |
function writeUTF8File($filename,$content) { $f=fopen($filename,"w+"); # Per scrivere l'UTF-8 aggiungiamo un "byte order mark" fwrite($f, pack("CCC",0xef,0xbb,0xbf)); fwrite($f,$content); fclose($f); } |
Funzione che fa il backup MySql in PHP
Per copiare il database dobbiamo connetterci al DB e leggerne tutte le tabelle. E’ conveniente usare SHOW TABLE per rendere dinamica la lettura delle tabelle e rendere quindi applicabile la funzione a tutti i database.
La funzione potrebbe essere la seguente:
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 |
function backup_tables($host,$user,$pass,$name,$tables = '*') { //Connessione al database $link = mysql_connect($host,$user,$pass); mysql_select_db($name,$link); //Possibilità di selezionare una tabella precisa 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); } //Ciclo sulle tabelle foreach($tables as $table) { $result = mysql_query('SELECT * FROM '.$table); $num_fields = mysql_num_fields($result); $return.= 'DROP TABLE '.$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]); $row[$j] = preg_match("\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"; } //Salvo su file usando la funzione writeUTF8File scritto in precedenza $file='backup/db-backup-'.time().'-'.(md5(implode(',',$tables))).'.sql'; writeUTF8File($file,$return); //Stampo la fine del processo echo('backup finished correctly.'); } |
Temporizzare il backup utilizzando Cronjob
Dopo aver creato un file per esempio cron.php contenente le due funzioni e la chiamata alla funzione di backup dobbiamo creare Cron Job e attivarlo sul server (in questo esempio usiamo server Linux):
Il Comando da eseguire è il seguente:
1 |
php /the/path/toyour/cronjob/file/cron.php |
La sintassi del cron è:
1 |
1 2 3 4 5 /path/cron.php arg1 arg2 |
Dove,
- 1: Minuto (0-59)
- 2: Ora (0-23)
- 3: Giorno (0-31)
- 4: Mese (0-12 [12 è riferito a Dicembre])
- 5: Giorno della settimana (0-7 [7 or 0 è riferito a Domenica])
- /path/cron.php – Script o comando da schedulare
Conclusioni e file cron.php
Scriviamo di seguito tutto il codice del file cron.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 |
function writeUTF8File($filename,$content) { $f=fopen($filename,"w+"); # Per scrivere l'UTF-8 aggiungiamo un "byte order mark" fwrite($f, pack("CCC",0xef,0xbb,0xbf)); fwrite($f,$content); fclose($f); } function backup_tables($host,$user,$pass,$name,$tables = '*') { //Connessione al database $link = mysql_connect($host,$user,$pass); mysql_select_db($name,$link); //Possibilità di selezionare una tabella precisa 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); } //Ciclo sulle tabelle foreach($tables as $table) { $result = mysql_query('SELECT * FROM '.$table); $num_fields = mysql_num_fields($result); $return.= 'DROP TABLE '.$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]); $row[$j] = preg_match("\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"; } //Salvo su file usando la funzione writeUTF8File scritto in precedenza $file='backup/db-backup-'.time().'-'.(md5(implode(',',$tables))).'.sql'; writeUTF8File($file,$return); //Stampo la fine del processo echo('backup finished correctly.'); } backup_tables($host,$user,$pass,$name); |