-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathPhpDatabaseBackup.php
More file actions
99 lines (83 loc) · 3.17 KB
/
PhpDatabaseBackup.php
File metadata and controls
99 lines (83 loc) · 3.17 KB
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
<?php
/*
* https://www.tutorialspoint.com/php/perform_mysql_backup_php.htm
*/
class PhpDatabaseBackup
{
private $dbhost;
private $dbuser;
private $dbpass;
private $dbname;
public function __construct(array $param)
{
$this->dbhost = $param['dbhost'];
$this->dbuser = $param['dbuser'];
$this->dbpass = $param['dbpass'];
$this->dbname = $param['dbname'];
}
public function sqlEscape(string $to_escape, string $subject)
{
return str_replace($to_escape, $to_escape . $to_escape, $subject);
}
public function mysql()
{
$db_connect = mysqli_connect($this->dbhost, $this->dbuser, $this->dbpass, $this->dbname);
$db_connect->set_charset("utf8");
$tables = array();
$sql = "SHOW TABLES";
$result = mysqli_query($db_connect, $sql);
while ($row = mysqli_fetch_row($result)) {
$tables[] = $row[0];
}
$sqlScript = "";
foreach ($tables as $table) {
$query = "SHOW CREATE TABLE $table";
$result = mysqli_query($db_connect, $query);
$row = mysqli_fetch_row($result);
$sqlScript .= "\n\n" . $row[1] . ";\n\n";
$query = "SELECT * FROM $table";
$result = mysqli_query($db_connect, $query);
$columnCount = mysqli_num_fields($result);
for ($i = 0; $i < $columnCount; $i++) {
while ($row = mysqli_fetch_row($result)) {
$sqlScript .= "INSERT INTO $table VALUES(";
for ($j = 0; $j < $columnCount; $j++) {
$row[$j] = $row[$j];
if (isset($row[$j])) {
if (is_numeric($row[$j])) {
$sqlScript .= $row[$j];
} else {
$sqlScript .= "'" . $this->sqlEscape('\'', $row[$j]) . "'";
}
} else {
$sqlScript .= "''";
}
if ($j < ($columnCount - 1)) {
$sqlScript .= ',';
}
}
$sqlScript .= ");\n";
}
}
$sqlScript .= "\n";
}
if (!empty($sqlScript)) {
$backup_file_name = $this->dbname . '_backup_' . time() . '.sql';
$fileHandler = fopen($backup_file_name, 'w+');
$number_of_lines = fwrite($fileHandler, $sqlScript);
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);
}
}
}