· 6 years ago · Oct 15, 2019, 09:58 AM
1<?php
2/* ----------------- BACKUP DEL DATABASE MYSQLi MACOS86.IT ------------------------------------------ */
3/* ------------------------------ By CIRO82 --------------------------------------------------------- */
4
5/* Report degli errori */
6error_reporting(E_ALL);
7
8/* Crea nuova istanza per la classe DatabaseBackup */
9$dbBackup = new DatabaseBackup();
10
11/* @Funzione chiamata - backupDatabase()
12 @parametri Primo Parametro: - Default : recupera tutte le tabelle - Tabelle specifiche - array(table1,table2,table3...)
13 CONSIGLIO DI LASCIARE DEFAULT(*);
14
15 Secondo Parametro: - (Cartella): Se non specificata ne crea una dove lo script risiede (CONSIGLIATO)
16*/
17
18$tables = '*'; /* Primo Parametro */
19$dbBackup->backupDatabase($tables,'BackupLogs'); /* Secondo Parametro */
20
21/* -----------------------------------------LA SEGUENTE PARTE NON VA COMPILATA -------------------------------------------------> */
22class DatabaseBackup{
23 private $hostname = ''; /* DB Hostname */
24 private $username = ''; /* DB Username */
25 private $password = ''; /* DB Password */
26 private $database = ''; /* Database Name */
27 private $characterSet = 'utf8'; /* Set di caratteri del DB */
28 private $backupDirectory = 'BackupLogs'; /* Cartella backup */
29
30 /* Connessione a Mysqli */
31 private $link = '';
32
33/*----------------------------------------- LA SEGUENTE PARTE VA COMPILATA -----------------------------------------------------> */
34 /* Classe del Constructor */
35 function __construct(){
36 /* Initializzazione delle variabili del DB */
37 $this->hostname = 'Nome del tuo host DB';
38 $this->username = 'nome utente DB';
39 $this->password = 'password del tuo DB';
40 $this->database = 'nome del tuo DB';
41 /* Funzione di chiamata all'inizializzazione del DB */
42 $this->initalizeDB();
43
44/* <----------------------------------------------------------------------------------------------------------------------------- */
45 }
46
47 /* Funzione per il collegamento a MySQL DB */
48 private function initalizeDB(){
49 $this->link = mysqli_connect($this->hostname, $this->username, $this->password, $this->database);
50 /* Messaggio se ci sono errori*/
51 if(mysqli_connect_error()){
52 die('Connection Error - '.mysqli_connect_errno().' : '.mysqli_connect_error());
53 }
54 /* Se non è definito un set caratteri imposta quello di default */
55 if(!mysqli_character_set_name($this->link)){
56 mysqli_set_charset($this->link,$this->characterSet);
57 }
58 }
59
60 /* Funzione di backup del Database */
61 public function backupDatabase($tables = '*',$backupDirectory = ''){
62 /* Se sono necessarie tutte le tabelle: */
63 if($tables == '*'){
64 $tables = array();
65 /* Recupera tutte le tabelle del database corrente */
66 $result = mysqli_query($this->link,"SHOW TABLES");
67 /* Passa attraverso tutte le righe e assegna l'array $tables */
68 while($row = mysqli_fetch_row($result)){
69 $tables[] = $row[0];
70 }
71 }else{
72 /* Se $tables è un array, assegnare direttamente altrimenti esplodere la stringa */
73 $tables = is_array($tables) ? $tables : explode(',',$tables);
74 }
75 /* Crea il database */
76 $sql = 'SET FOREIGN_KEY_CHECKS = 0;'."\n".'CREATE DATABASE IF NOT EXISTS `'.$this->database."`;\n";
77 /* Usa il database */
78 $sql .= 'USE `'.$this->database.'`;';
79
80 /* Passa attraverso tutti le $tables */
81 foreach($tables as $table){
82 /* Messaggio di output */
83 echo 'Salvataggio : `'.$table.'` : ';
84
85 /* Recupera i dettagli della tabella */
86 $tableDetails = mysqli_query($this->link, "SELECT * FROM ".$table);
87
88 /* Controlla il numero di colonne nella tabella */
89 $totalCols = mysqli_num_fields($tableDetails);
90
91 /* Se la tabella esiste, droppala */
92 $sql .= "\n\nDROP TABLE IF EXISTS `".$table."`;\n";
93 /* Crea la struttura dela tabella */
94 $result1 = mysqli_fetch_row(mysqli_query($this->link,'SHOW CREATE TABLE '.$table));
95 $sql .= $result1[1].";\n\n";
96
97
98 while($row = mysqli_fetch_row($tableDetails)){
99 $sql .= 'INSERT INTO `'.$table.'` VALUES(';
100 for($j=0; $j<$totalCols; $j++){
101 $row[$j] = preg_replace("/\n/","\\n",addslashes($row[$j]));
102 if (isset($row[$j]))
103 {
104 $sql .= '"'.$row[$j].'"' ;
105 }
106 else
107 {
108 $sql.= '""';
109 }
110
111 if ($j < ($totalCols-1))
112 {
113 $sql .= ', ';
114 }
115 }
116 $sql .= "); \n";
117 }
118 echo 'Completato <br/>';
119 }
120 $sql .= 'SET FOREIGN_KEY_CHECKS = 1;';
121 /* Se il secondo parametro non è stato specificato, verrà usato quello di default */
122 $backupDirectory = ($backupDirectory == '') ? $this->backupDirectory : $backupDirectory;
123 if($this->logDatabase($sql,$backupDirectory)){
124 echo '<h4>Database <span style="color:#7D0097">`'.$this->database.'`</span>esportato correttamente nella cartella - <span style="color:#1CAD7A"> `'.$backupDirectory.'`</span><h4>';exit;
125 }else{
126 echo '<h2>Errore esportazione database '.$this->database.'<h2>';exit;
127 }
128
129 }
130
131 /* Funzione di salvataggio del database */
132 private function logDatabase($sql,$backupDirectory = ''){
133 if(!$sql){
134 return false;
135 }
136
137 if(!file_exists($backupDirectory)){
138 if(mkdir($backupDirectory)){
139 $filename = 'log_'.$this->database.date('Y-m-d_H-i-s');
140 $fileHandler = fopen($backupDirectory.'/'.$filename.'.sql','w+');
141 fwrite($fileHandler,$sql);
142 fclose($fileHandler);
143 return true;
144 }
145 }else{
146 $filename = 'log_'.$this->database.date('Y-m-d_H-i-s');
147 $fileHandler = fopen($backupDirectory.'/'.$filename.'.sql','w+');
148 fwrite($fileHandler,$sql);
149 fclose($fileHandler);
150 return true;
151 }
152 return false;
153 }
154}