Related
Here's the information I have:
I am working with a Linux based system using MySQL and PHP5. I need to be able to generate a mysqldump from within a .php file, and then have that dump be stored in a file on the server in a location I would specify.
As I'm a PHP nooblet, I'd like someone to give me some assistance, guidance, or code, that would do what I require. This would have to be run remotely from the Internet.
You can use the exec() function to execute an external command.
Note: between shell_exec() and exec(), I would choose the second one, which doesn't return the output to the PHP script -- no need for the PHP script to get the whole SQL dump as a string : you only need it written to a file, and this can be done by the command itself.
That external command will :
be a call to mysqldump, with the right parameters,
and redirect the output to a file.
For example :
mysqldump --user=... --password=... --host=... DB_NAME > /path/to/output/file.sql
Which means your PHP code would look like this :
exec('mysqldump --user=... --password=... --host=... DB_NAME > /path/to/output/file.sql');
Of course, up to you to use the right connection information, replacing the ... with those.
If you want to create a backup to download it via the browser, you also can do this without using a file.
The php function passthru() will directly redirect the output of mysqldump to the browser. In this example it also will be zipped.
Pro: You don't have to deal with temp files.
Con: Won't work on Windows. May have limits with huge datasets.
<?php
$DBUSER="user";
$DBPASSWD="password";
$DATABASE="user_db";
$filename = "backup-" . date("d-m-Y") . ".sql.gz";
$mime = "application/x-gzip";
header( "Content-Type: " . $mime );
header( 'Content-Disposition: attachment; filename="' . $filename . '"' );
$cmd = "mysqldump -u $DBUSER --password=$DBPASSWD $DATABASE | gzip --best";
passthru( $cmd );
exit(0);
?>
Take a look here: https://github.com/ifsnop/mysqldump-php ! It is a native solution written in php.
You can install it using composer, and it is as easy as doing:
<?php
use Ifsnop\Mysqldump as IMysqldump;
try {
$dump = new IMysqldump\Mysqldump('database', 'username', 'password');
$dump->start('storage/work/dump.sql');
} catch (\Exception $e) {
echo 'mysqldump-php error: ' . $e->getMessage();
}
?>
It supports advanced users, with lots of options copied from the original mysqldump.
All the options are explained at the github page, but more or less are auto-explicative:
$dumpSettingsDefault = array(
'include-tables' => array(),
'exclude-tables' => array(),
'compress' => 'None',
'no-data' => false,
'add-drop-database' => false,
'add-drop-table' => false,
'single-transaction' => true,
'lock-tables' => false,
'add-locks' => true,
'extended-insert' => true,
'disable-foreign-keys-check' => false,
'where' => '',
'no-create-info' => false
);
For security reasons, it's recommended to specify the password in a configuration file and not in the command (a user can execute a ps aux | grep mysqldump and see the password).
//create a temporary file
$file = tempnam(sys_get_temp_dir(), 'mysqldump');
//store the configuration options
file_put_contents($file, "[mysqldump]
user={$user}
password=\"{$password}\"");
//execute the command and output the result
passthru("mysqldump --defaults-file=$file {$dbname}");
//delete the temporary file
unlink($file);
Here you can find a comprehensive solution to dump mysql structure and data like in PMA (and without using exec, passthru etc.):
https://github.com/antarasi/MySQL-Dump-with-Foreign-keys
It is fork of dszymczuk project with my enhancements.
The usage is simple
<?php
//MySQL connection parameters
$dbhost = 'localhost';
$dbuser = 'dbuser';
$dbpsw = 'pass';
$dbname = 'dbname';
//Connects to mysql server
$connessione = #mysql_connect($dbhost,$dbuser,$dbpsw);
//Set encoding
mysql_query("SET CHARSET utf8");
mysql_query("SET NAMES 'utf8' COLLATE 'utf8_general_ci'");
//Includes class
require_once('FKMySQLDump.php');
//Creates a new instance of FKMySQLDump: it exports without compress and base-16 file
$dumper = new FKMySQLDump($dbname,'fk_dump.sql',false,false);
$params = array(
//'skip_structure' => TRUE,
//'skip_data' => TRUE,
);
//Make dump
$dumper->doFKDump($params);
?>
works like a charm :-)
MajorLeo's answer point me in the right direction but it didn't worked for me. I've found this site that follows the same approach and did work.
$dir = "path/to/file/";
$filename = "backup" . date("YmdHis") . ".sql.gz";
$db_host = "host";
$db_username = "username";
$db_password = "password";
$db_database = "database";
$cmd = "mysqldump -h {$db_host} -u {$db_username} --password={$db_password} {$db_database} | gzip > {$dir}{$filename}";
exec($cmd);
header("Content-type: application/octet-stream");
header("Content-Disposition: attachment; filename=\"$filename\"");
passthru("cat {$dir}{$filename}");
I hope it helps someone else!
As long as you are allowed to use exec(), you can execute shell commands through your PHP code.
So assuming you know how to write the mysqldump in the command line, i.e.
mysqldump -u [username] -p [database] > [database].sql
then you can use this as the parameter to exec() function.
exec("mysqldump -u mysqluser -p my_database > my_database_dump.sql");
Well, you can always use PHP's system function call.
http://php.net/manual/en/function.system.php
http://www.php.net/manual/en/function.exec.php
That runs any command-line program from PHP.
<?php
exec('mysqldump --all-databases > /your/path/to/test.sql');
?>
You can extend the command with any options mysqldump takes ofcourse. Use man mysqldump for more options (but I guess you knew that ;))
global $wpdb;
$export_posts = $wpdb->prefix . 'export_posts';
$backupFile = $_GET['targetDir'].'export-gallery.sql';
$dbhost=DB_HOST;
$dbuser=DB_USER;
$dbpass=DB_PASSWORD;
$db=DB_NAME;
$path_to_mysqldump = "D:\xampp_5.6\mysql\bin";
$query= "D:\\xampp_5.6\mysql\bin\mysqldump.exe -u$dbuser -p$dbpass $db $export_posts> $backupFile";
exec($query);
echo $query;
To dump database using shell_exec(), below is the method :
shell_exec('mysqldump -h localhost -u username -ppassword databasename | gzip > dbname.sql.gz');
None of the above codes worked for me. I am using windows.
Below Code worked for me...
$sql = "SELECT * FROM $tableName WHERE yourclause";
$result = $conn->query($sql);
if($result){
if ($result->num_rows > 0) {
$myfile = fopen("daily_events_$district.sql", "w") or die("Unable to open file!");
while($row = $result->fetch_assoc()) {
$rowToString = implode("','",$row);
$writeToFile = "INSERT INTO $tableName VALUES('$rowToString');". PHP_EOL;
fwrite($myfile,$writeToFile);
}
echo "File saved successfully";
}
} else {
echo "No result found";
}
This will save file in your project folder according to your query whatever data you want.
<?php
$toDay = date('d-m-Y');
$dbhost = "localhost";
$dbuser = "YOUR DB USER";
$dbpass = "USER PASSWORD";
$dbname = "DB NAME";
exec("mysqldump --user=$dbuser --password='$dbpass' --host=$dbhost $dbname > /home/....../public_html/".$toDay."_DB.sql");
?>
Here's the information I have:
I am working with a Linux based system using MySQL and PHP5. I need to be able to generate a mysqldump from within a .php file, and then have that dump be stored in a file on the server in a location I would specify.
As I'm a PHP nooblet, I'd like someone to give me some assistance, guidance, or code, that would do what I require. This would have to be run remotely from the Internet.
You can use the exec() function to execute an external command.
Note: between shell_exec() and exec(), I would choose the second one, which doesn't return the output to the PHP script -- no need for the PHP script to get the whole SQL dump as a string : you only need it written to a file, and this can be done by the command itself.
That external command will :
be a call to mysqldump, with the right parameters,
and redirect the output to a file.
For example :
mysqldump --user=... --password=... --host=... DB_NAME > /path/to/output/file.sql
Which means your PHP code would look like this :
exec('mysqldump --user=... --password=... --host=... DB_NAME > /path/to/output/file.sql');
Of course, up to you to use the right connection information, replacing the ... with those.
If you want to create a backup to download it via the browser, you also can do this without using a file.
The php function passthru() will directly redirect the output of mysqldump to the browser. In this example it also will be zipped.
Pro: You don't have to deal with temp files.
Con: Won't work on Windows. May have limits with huge datasets.
<?php
$DBUSER="user";
$DBPASSWD="password";
$DATABASE="user_db";
$filename = "backup-" . date("d-m-Y") . ".sql.gz";
$mime = "application/x-gzip";
header( "Content-Type: " . $mime );
header( 'Content-Disposition: attachment; filename="' . $filename . '"' );
$cmd = "mysqldump -u $DBUSER --password=$DBPASSWD $DATABASE | gzip --best";
passthru( $cmd );
exit(0);
?>
Take a look here: https://github.com/ifsnop/mysqldump-php ! It is a native solution written in php.
You can install it using composer, and it is as easy as doing:
<?php
use Ifsnop\Mysqldump as IMysqldump;
try {
$dump = new IMysqldump\Mysqldump('database', 'username', 'password');
$dump->start('storage/work/dump.sql');
} catch (\Exception $e) {
echo 'mysqldump-php error: ' . $e->getMessage();
}
?>
It supports advanced users, with lots of options copied from the original mysqldump.
All the options are explained at the github page, but more or less are auto-explicative:
$dumpSettingsDefault = array(
'include-tables' => array(),
'exclude-tables' => array(),
'compress' => 'None',
'no-data' => false,
'add-drop-database' => false,
'add-drop-table' => false,
'single-transaction' => true,
'lock-tables' => false,
'add-locks' => true,
'extended-insert' => true,
'disable-foreign-keys-check' => false,
'where' => '',
'no-create-info' => false
);
For security reasons, it's recommended to specify the password in a configuration file and not in the command (a user can execute a ps aux | grep mysqldump and see the password).
//create a temporary file
$file = tempnam(sys_get_temp_dir(), 'mysqldump');
//store the configuration options
file_put_contents($file, "[mysqldump]
user={$user}
password=\"{$password}\"");
//execute the command and output the result
passthru("mysqldump --defaults-file=$file {$dbname}");
//delete the temporary file
unlink($file);
Here you can find a comprehensive solution to dump mysql structure and data like in PMA (and without using exec, passthru etc.):
https://github.com/antarasi/MySQL-Dump-with-Foreign-keys
It is fork of dszymczuk project with my enhancements.
The usage is simple
<?php
//MySQL connection parameters
$dbhost = 'localhost';
$dbuser = 'dbuser';
$dbpsw = 'pass';
$dbname = 'dbname';
//Connects to mysql server
$connessione = #mysql_connect($dbhost,$dbuser,$dbpsw);
//Set encoding
mysql_query("SET CHARSET utf8");
mysql_query("SET NAMES 'utf8' COLLATE 'utf8_general_ci'");
//Includes class
require_once('FKMySQLDump.php');
//Creates a new instance of FKMySQLDump: it exports without compress and base-16 file
$dumper = new FKMySQLDump($dbname,'fk_dump.sql',false,false);
$params = array(
//'skip_structure' => TRUE,
//'skip_data' => TRUE,
);
//Make dump
$dumper->doFKDump($params);
?>
works like a charm :-)
MajorLeo's answer point me in the right direction but it didn't worked for me. I've found this site that follows the same approach and did work.
$dir = "path/to/file/";
$filename = "backup" . date("YmdHis") . ".sql.gz";
$db_host = "host";
$db_username = "username";
$db_password = "password";
$db_database = "database";
$cmd = "mysqldump -h {$db_host} -u {$db_username} --password={$db_password} {$db_database} | gzip > {$dir}{$filename}";
exec($cmd);
header("Content-type: application/octet-stream");
header("Content-Disposition: attachment; filename=\"$filename\"");
passthru("cat {$dir}{$filename}");
I hope it helps someone else!
As long as you are allowed to use exec(), you can execute shell commands through your PHP code.
So assuming you know how to write the mysqldump in the command line, i.e.
mysqldump -u [username] -p [database] > [database].sql
then you can use this as the parameter to exec() function.
exec("mysqldump -u mysqluser -p my_database > my_database_dump.sql");
Well, you can always use PHP's system function call.
http://php.net/manual/en/function.system.php
http://www.php.net/manual/en/function.exec.php
That runs any command-line program from PHP.
<?php
exec('mysqldump --all-databases > /your/path/to/test.sql');
?>
You can extend the command with any options mysqldump takes ofcourse. Use man mysqldump for more options (but I guess you knew that ;))
global $wpdb;
$export_posts = $wpdb->prefix . 'export_posts';
$backupFile = $_GET['targetDir'].'export-gallery.sql';
$dbhost=DB_HOST;
$dbuser=DB_USER;
$dbpass=DB_PASSWORD;
$db=DB_NAME;
$path_to_mysqldump = "D:\xampp_5.6\mysql\bin";
$query= "D:\\xampp_5.6\mysql\bin\mysqldump.exe -u$dbuser -p$dbpass $db $export_posts> $backupFile";
exec($query);
echo $query;
To dump database using shell_exec(), below is the method :
shell_exec('mysqldump -h localhost -u username -ppassword databasename | gzip > dbname.sql.gz');
None of the above codes worked for me. I am using windows.
Below Code worked for me...
$sql = "SELECT * FROM $tableName WHERE yourclause";
$result = $conn->query($sql);
if($result){
if ($result->num_rows > 0) {
$myfile = fopen("daily_events_$district.sql", "w") or die("Unable to open file!");
while($row = $result->fetch_assoc()) {
$rowToString = implode("','",$row);
$writeToFile = "INSERT INTO $tableName VALUES('$rowToString');". PHP_EOL;
fwrite($myfile,$writeToFile);
}
echo "File saved successfully";
}
} else {
echo "No result found";
}
This will save file in your project folder according to your query whatever data you want.
<?php
$toDay = date('d-m-Y');
$dbhost = "localhost";
$dbuser = "YOUR DB USER";
$dbpass = "USER PASSWORD";
$dbname = "DB NAME";
exec("mysqldump --user=$dbuser --password='$dbpass' --host=$dbhost $dbname > /home/....../public_html/".$toDay."_DB.sql");
?>
I'm testing this script on the local server
$dump_path = "backups";
$host = "localhost";
$user = "root";
$pass = "";
$command=$dump_path.'mysqldump -h '.$host.' -u '.$user.' dental > dental_b.sql';
if (system($command)) {
echo "YES" ;
} else {
echo "Error" ;
}
But why isn't that script executed and shows an error although all data from the DB is true.
I'm pretty sure you don't need the host option if you're using mysqldump on localhost. The way you are concatenating your command looks messed up to me. Let me show you what works for me. I use this all the time:
<?php
$user = "root";
$pass = "";
$database = "dental";
// File name
$file_name = 'dental_b.' . date('mdY.Hia') . '.sql.gz';
// Storage directory
$storage_dir = __DIR__ . '/backups';
if( ! is_dir( $storage_dir ) )
mkdir( $storage_dir, 0777, TRUE );
// Absolute path to new file
$absolute_path = $storage_dir . '/' . $file_name;
// Create the backup file
exec( 'mysqldump -u ' . $user .
' -p' . $pass .
' ' . $database .
' | gzip > ' . $absolute_path );
Yes, I am gzipping the file. I think you'll find this is a good option for storage, emailing, etc.
EDIT ---
If you are not using a password, you should not use -p. You'd want to alter the command in that case.
I have had written the following snippet that generates the mysql database dump and saves it on the server:
public function save_db_backup()
{
$DBUSER=$this->db->username;
$DBPASSWD=$this->db->password;
$DATABASE=$this->db->database;
$filename = $DATABASE . "-" . date("Y-m-d_H-i-s") . ".sql.gz";
$save_path = $_SERVER['DOCUMENT_ROOT'] . '/application/assets/db_backups/' . $filename;
$cmd = "mysqldump -u $DBUSER --password=$DBPASSWD $DATABASE | gzip --best > " . $save_path;
exec( $cmd );
}
It has been working fine on my other server. But after moving my site to this new server, it has suddenly stopped working i.e. database backup file is not being saved at the path specified. Also, I have checked exec is enabled on the server plus the directory is readable and also writeable:
is_readable($_SERVER['DOCUMENT_ROOT'] . '/application/assets/db_backups/') // true
is_writable($_SERVER['DOCUMENT_ROOT'] . '/application/assets/db_backups/') // true
I have checked and the database credentials are alright. I have tried with the path to mysqldump and that didn't work either:
$cmd = "/usr/bin/mysqldump -u $DBUSER --password=$DBPASSWD $DATABASE | gzip --best > " . $save_path;
What problem could there possibly be?
You should check what user launches the command, and then if the dir is readable and also writeable by THAT user.
If you are launching it from a PHP script, it's the probable cause.
Here's the information I have:
I am working with a Linux based system using MySQL and PHP5. I need to be able to generate a mysqldump from within a .php file, and then have that dump be stored in a file on the server in a location I would specify.
As I'm a PHP nooblet, I'd like someone to give me some assistance, guidance, or code, that would do what I require. This would have to be run remotely from the Internet.
You can use the exec() function to execute an external command.
Note: between shell_exec() and exec(), I would choose the second one, which doesn't return the output to the PHP script -- no need for the PHP script to get the whole SQL dump as a string : you only need it written to a file, and this can be done by the command itself.
That external command will :
be a call to mysqldump, with the right parameters,
and redirect the output to a file.
For example :
mysqldump --user=... --password=... --host=... DB_NAME > /path/to/output/file.sql
Which means your PHP code would look like this :
exec('mysqldump --user=... --password=... --host=... DB_NAME > /path/to/output/file.sql');
Of course, up to you to use the right connection information, replacing the ... with those.
If you want to create a backup to download it via the browser, you also can do this without using a file.
The php function passthru() will directly redirect the output of mysqldump to the browser. In this example it also will be zipped.
Pro: You don't have to deal with temp files.
Con: Won't work on Windows. May have limits with huge datasets.
<?php
$DBUSER="user";
$DBPASSWD="password";
$DATABASE="user_db";
$filename = "backup-" . date("d-m-Y") . ".sql.gz";
$mime = "application/x-gzip";
header( "Content-Type: " . $mime );
header( 'Content-Disposition: attachment; filename="' . $filename . '"' );
$cmd = "mysqldump -u $DBUSER --password=$DBPASSWD $DATABASE | gzip --best";
passthru( $cmd );
exit(0);
?>
Take a look here: https://github.com/ifsnop/mysqldump-php ! It is a native solution written in php.
You can install it using composer, and it is as easy as doing:
<?php
use Ifsnop\Mysqldump as IMysqldump;
try {
$dump = new IMysqldump\Mysqldump('database', 'username', 'password');
$dump->start('storage/work/dump.sql');
} catch (\Exception $e) {
echo 'mysqldump-php error: ' . $e->getMessage();
}
?>
It supports advanced users, with lots of options copied from the original mysqldump.
All the options are explained at the github page, but more or less are auto-explicative:
$dumpSettingsDefault = array(
'include-tables' => array(),
'exclude-tables' => array(),
'compress' => 'None',
'no-data' => false,
'add-drop-database' => false,
'add-drop-table' => false,
'single-transaction' => true,
'lock-tables' => false,
'add-locks' => true,
'extended-insert' => true,
'disable-foreign-keys-check' => false,
'where' => '',
'no-create-info' => false
);
For security reasons, it's recommended to specify the password in a configuration file and not in the command (a user can execute a ps aux | grep mysqldump and see the password).
//create a temporary file
$file = tempnam(sys_get_temp_dir(), 'mysqldump');
//store the configuration options
file_put_contents($file, "[mysqldump]
user={$user}
password=\"{$password}\"");
//execute the command and output the result
passthru("mysqldump --defaults-file=$file {$dbname}");
//delete the temporary file
unlink($file);
Here you can find a comprehensive solution to dump mysql structure and data like in PMA (and without using exec, passthru etc.):
https://github.com/antarasi/MySQL-Dump-with-Foreign-keys
It is fork of dszymczuk project with my enhancements.
The usage is simple
<?php
//MySQL connection parameters
$dbhost = 'localhost';
$dbuser = 'dbuser';
$dbpsw = 'pass';
$dbname = 'dbname';
//Connects to mysql server
$connessione = #mysql_connect($dbhost,$dbuser,$dbpsw);
//Set encoding
mysql_query("SET CHARSET utf8");
mysql_query("SET NAMES 'utf8' COLLATE 'utf8_general_ci'");
//Includes class
require_once('FKMySQLDump.php');
//Creates a new instance of FKMySQLDump: it exports without compress and base-16 file
$dumper = new FKMySQLDump($dbname,'fk_dump.sql',false,false);
$params = array(
//'skip_structure' => TRUE,
//'skip_data' => TRUE,
);
//Make dump
$dumper->doFKDump($params);
?>
works like a charm :-)
MajorLeo's answer point me in the right direction but it didn't worked for me. I've found this site that follows the same approach and did work.
$dir = "path/to/file/";
$filename = "backup" . date("YmdHis") . ".sql.gz";
$db_host = "host";
$db_username = "username";
$db_password = "password";
$db_database = "database";
$cmd = "mysqldump -h {$db_host} -u {$db_username} --password={$db_password} {$db_database} | gzip > {$dir}{$filename}";
exec($cmd);
header("Content-type: application/octet-stream");
header("Content-Disposition: attachment; filename=\"$filename\"");
passthru("cat {$dir}{$filename}");
I hope it helps someone else!
As long as you are allowed to use exec(), you can execute shell commands through your PHP code.
So assuming you know how to write the mysqldump in the command line, i.e.
mysqldump -u [username] -p [database] > [database].sql
then you can use this as the parameter to exec() function.
exec("mysqldump -u mysqluser -p my_database > my_database_dump.sql");
Well, you can always use PHP's system function call.
http://php.net/manual/en/function.system.php
http://www.php.net/manual/en/function.exec.php
That runs any command-line program from PHP.
<?php
exec('mysqldump --all-databases > /your/path/to/test.sql');
?>
You can extend the command with any options mysqldump takes ofcourse. Use man mysqldump for more options (but I guess you knew that ;))
global $wpdb;
$export_posts = $wpdb->prefix . 'export_posts';
$backupFile = $_GET['targetDir'].'export-gallery.sql';
$dbhost=DB_HOST;
$dbuser=DB_USER;
$dbpass=DB_PASSWORD;
$db=DB_NAME;
$path_to_mysqldump = "D:\xampp_5.6\mysql\bin";
$query= "D:\\xampp_5.6\mysql\bin\mysqldump.exe -u$dbuser -p$dbpass $db $export_posts> $backupFile";
exec($query);
echo $query;
To dump database using shell_exec(), below is the method :
shell_exec('mysqldump -h localhost -u username -ppassword databasename | gzip > dbname.sql.gz');
None of the above codes worked for me. I am using windows.
Below Code worked for me...
$sql = "SELECT * FROM $tableName WHERE yourclause";
$result = $conn->query($sql);
if($result){
if ($result->num_rows > 0) {
$myfile = fopen("daily_events_$district.sql", "w") or die("Unable to open file!");
while($row = $result->fetch_assoc()) {
$rowToString = implode("','",$row);
$writeToFile = "INSERT INTO $tableName VALUES('$rowToString');". PHP_EOL;
fwrite($myfile,$writeToFile);
}
echo "File saved successfully";
}
} else {
echo "No result found";
}
This will save file in your project folder according to your query whatever data you want.
<?php
$toDay = date('d-m-Y');
$dbhost = "localhost";
$dbuser = "YOUR DB USER";
$dbpass = "USER PASSWORD";
$dbname = "DB NAME";
exec("mysqldump --user=$dbuser --password='$dbpass' --host=$dbhost $dbname > /home/....../public_html/".$toDay."_DB.sql");
?>