-
Notifications
You must be signed in to change notification settings - Fork 0
/
backup_function.php
85 lines (64 loc) · 2.16 KB
/
backup_function.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
<?php
error_reporting(0);
function backDb($host, $user, $pass, $dbname, $tables = '*'){
$conn = new mysqli($host, $user, $pass, $dbname);
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
if($tables == '*'){
$tables = array();
$sql = "SHOW TABLES";
$query = $conn->query($sql);
while($row = $query->fetch_row()){
$tables[] = $row[0];
}
}
else{
$tables = is_array($tables) ? $tables : explode(',',$tables);
}
$outsql = '';
foreach ($tables as $table) {
$sql = "SHOW CREATE TABLE $table";
$query = $conn->query($sql);
$row = $query->fetch_row();
$outsql .= "\n\n" . $row[1] . ";\n\n";
$sql = "SELECT * FROM $table";
$query = $conn->query($sql);
$columnCount = $query->field_count;
for ($i = 0; $i < $columnCount; $i ++) {
while ($row = $query->fetch_row()) {
$outsql .= "INSERT INTO $table VALUES(";
for ($j = 0; $j < $columnCount; $j ++) {
$row[$j] = $row[$j];
if (isset($row[$j])) {
$outsql .= '"' . $row[$j] . '"';
} else {
$outsql .= '""';
}
if ($j < ($columnCount - 1)) {
$outsql .= ',';
}
}
$outsql .= ");\n";
}
}
$outsql .= "\n";
}
$backup_file_name = $dbname . '_database.sql';
$fileHandler = fopen($backup_file_name, 'w+');
fwrite($fileHandler, $outsql);
fclose($fileHandler);
header('Content-Description: File Transfer');
header('Content-Type: application/octet-stream');
header('Content-Disposition: attachment; filename=' . basename($backup_file_name));
header('Content-Transfer-Encoding: binary');
header('Expires: 0');
header('Cache-Control: must-revalidate');
header('Pragma: public');
header('Content-Length: ' . filesize($backup_file_name));
ob_clean();
flush();
readfile($backup_file_name);
exec('rm ' . $backup_file_name);
}
?>