122

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.

hakre
  • 178,314
  • 47
  • 389
  • 754
Thomas Ward
  • 2,308
  • 5
  • 31
  • 46
  • 2
    Check [this](http://www.php-mysql-tutorial.com/wikis/mysql-tutorials/using-php-to-backup-mysql-databases.aspx). I would use `mysqldump` by `system()`. – dave Jul 19 '11 at 16:24
  • possible duplicate of [Easy way to export a SQL table without access to the server or phpMyADMIN](http://stackoverflow.com/questions/81934/easy-way-to-export-a-sql-table-without-access-to-the-server-or-phpmyadmin) – T.Todua Jun 01 '15 at 07:49
  • This one helps to create mysqldump with help a php file. http://www.kvcodes.com/2017/10/php-create-mysql-backup/ – Kvvaradha Oct 04 '17 at 11:04
  • Do not rely on exec() or system(), because most times they are disabled on shared hostings. Answer should implement a proper way to generate a database dump without running external programs. – diego Dec 24 '19 at 00:45

15 Answers15

166

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.

Pascal MARTIN
  • 374,560
  • 73
  • 631
  • 650
  • 2
    I will take a stab at this shortly. Is there any way to generate output on the PHP page when it has completed saying "Dump complete!" or something? – Thomas Ward Jul 19 '11 at 16:32
  • 6
    `exec()` will not return until the command is finished ; so, just put some `echo "dump complete"` after calling `exec()` – Pascal MARTIN Jul 19 '11 at 16:34
  • @The Evil Phoenix: from php.net, `exec()` function reference: "To get the output of the executed command, be sure to set and use the output parameter.". – dave Jul 19 '11 at 16:35
  • 7
    This helped me today - and a note for users of osx lion: mysqldump shortcut wasn't set up for me when I installed mysql, so I had to find it - here's the path: `/usr/local/mysql/bin/mysqldump` – totallyNotLizards Apr 04 '12 at 09:34
  • Is this fast to execute 100Mb+ worth of database file size? – PinoyStackOverflower Nov 12 '12 at 06:09
  • 4
    Your comment, jammypeach, saved my life. Please note that any1 might need this little addition: '/usr/local/mysql/bin/mysqldump -u...' – helpse Jun 19 '13 at 04:21
  • It not works for me. I must execute this code `exec("C:\\xampp\\mysql\\bin\\mysqldump dr2014 -u root > $patName");` – ABA Sep 04 '14 at 17:12
  • 1
    Note for Windows users: In Windows you have to specify the complete path to mysqldump.exe, e.g. `exec("C:/pathto/mysql/bin/mysqldump.exe ");` – pogosama Nov 05 '15 at 12:48
  • This works for me - and I have used it before. But on this particular server - I am having lots of trouble with permissions and no help from the admins. Is there a way to just display the output on the page? ... desperate :/ –  Dec 28 '15 at 00:45
  • thank you sir for the helpful information. I'm new to web developing and hosting. I heard that using exec() is not allowed on most web hosting service providers. and when I check web hosting sites features , they say that they allow `cron jobs` , does cron jobs **mean** that the host allows `exec()` function ? thanks , and sorry for being noob. – Accountant م Aug 18 '16 at 21:38
  • Just a note, in some servers `exec` and `shell_exec` are disabled due to security issues. Example: [Umbler](https://www.umbler.com/)'s servers. – giovannipds Feb 28 '18 at 22:42
  • If your server has `exec` and `shell_exec` disabled, check [diego's answer](https://stackoverflow.com/a/24964928/842768). – giovannipds Feb 28 '18 at 23:10
  • To get this to work, I had to replace `mysqldump` with `/usr/bin/mysqldump`. I also had to change `password=mystrongpassword` to `password="mystrongpassword"`. – ban-geoengineering Oct 16 '19 at 14:22
86

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);
?>
Steve Westbrook
  • 1,670
  • 2
  • 20
  • 21
MajorLeo
  • 869
  • 6
  • 2
27

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
);
diego
  • 439
  • 4
  • 6
  • 2
    Even on servers which have `exec` and/or `shell_exec` disabled by security, [mysqldump-php](https://github.com/ifsnop/mysqldump-php) works great! Just tried it right now on [Umbler](https://www.umbler.com)'s servers and got the dump successfully. Thank you very much for the tip! – giovannipds Feb 28 '18 at 23:08
  • this is perfect for servers that dont have mysql shell commands available also! – Andrej May 18 '18 at 17:46
9

Please reffer to the following link which contains a scriptlet that will help you: http://davidwalsh.name/backup-mysql-database-php

Note: This script may contain bugs with NULL data types

Mike Mackintosh
  • 13,156
  • 6
  • 54
  • 83
André Puel
  • 7,716
  • 7
  • 45
  • 78
7

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);
Constantin Galbenu
  • 14,628
  • 3
  • 23
  • 41
5

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 :-)

ANTARA
  • 689
  • 1
  • 11
  • 19
  • It does work - but it produces a different output than the PHPMYADMIN mysqldump. Why ? There is data missing, while my PHPMYADMIN backup is complete. – ledawg Sep 25 '15 at 13:07
  • @Ledew-de: Data should not be included in dump only if option skip_data=>true is passed as a parameter – ANTARA Sep 26 '15 at 20:11
3

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!

Matías Cánepa
  • 5,201
  • 4
  • 49
  • 88
  • Yours here returns the output to the end user does it not? I.E. upon execution it outputs it in a way you could copy/paste? If so then this wouldn't achieve what the accepted answer did - just creates the file on the server so I could grab it by scp. – Thomas Ward Oct 19 '15 at 22:00
  • @ThomasW. This code does two things: it generates a file saved on server and prompt the download dialog. If you just want to store the file, then don't do the header() and passthru() part. And if you need the just the file location, you can always echo the $dir & $filename variables....No matter what you choose, you still can access the file via SCP – Matías Cánepa Oct 19 '15 at 22:49
3

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");
charliefortune
  • 2,450
  • 2
  • 20
  • 41
0

Here's another native PHP based option: https://github.com/2createStudio/shuttle-export

Emil M
  • 1,042
  • 12
  • 18
0

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;
0

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.

Your Common Sense
  • 152,517
  • 33
  • 193
  • 313
0

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.

jazztickets
  • 9
  • 1
  • 1
0

<?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 ;))

Rem.co
  • 3,785
  • 3
  • 25
  • 37
-1

To dump database using shell_exec(), below is the method :

shell_exec('mysqldump -h localhost -u username -ppassword databasename  | gzip > dbname.sql.gz');
Digisha
  • 345
  • 3
  • 5
-2
<?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");


?>
Bill the Lizard
  • 369,957
  • 201
  • 546
  • 842