Using a .php file to generate a MySQL dump

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.

Leave a Comment