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.
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).<?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 ;))You can use the
exec()
function to execute an external command.Note: between
shell_exec()
andexec()
, 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 :
mysqldump
, with the right parameters,For example :
Which means your PHP code would look like this :
Of course, up to you to use the right connection information, replacing the
...
with those.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.
then you can use this as the parameter to exec() function.
Here's another native PHP based option: https://github.com/2createStudio/shuttle-export
To dump database using shell_exec(), below is the method :