I'm trying to allow a simple PHP form to create a backup of a database. Based off my research thus far the best approach is using PHP's exec function. When I run my PHP script, it is running under user apache
and the exec function's second and third parameters return and empty array and 1
, respectively.
When I log in to my AWS EC2 instance and copy/paste the command as it was passed to the exec function it executes just fine! The only difference I can tell is that I'm logged in as user ec2-user
instead of apache. I started messing around with the /etc/sudoers
file, but all that did was break my svn-post-commit-hook-update-project script (which I'd created by following this tutorial ).
For reference, here are the two database-copy attempts I've made, using PHP and the exec function:
// method 1
$command = "/usr/bin/sudo /usr/bin/mysqldump -u ".getDBUsername()." $password ".getDBDatabase()." | mysql -u ".getDBUsername()." $password $new_db";
$output = array();
$return = null;
$output = exec($command, $output, $return);
var_dump($output);
The second try I hav emade is piping the mysqldump to a .sql file then reading it back in, but the .sql file never gets populated (though it will be created).
// method 2
$dump_command = "sudo mysqldump -u ".getDBUsername()." $password".getDBDatabase()." > ./temp.sql";
$output = null;
$return_var = null;
exec($dump_command, $output, $return_var);
var_dump($output);
exec("sudo mysql $new_db -u ".getDBUsername()." -p".getDBPassword()." < ./temp.sql");
Notes:
$password
does contain the -p
tag if the password is set (and yes, without a space between it and the password). chown
command, but it hasn't made a difference. Any suggestions on what to try? I suspect simply giving user apache
the permissions that ec2-user
has would suffice, but haven't figured out how to do that, and again, my edits to /etc/sudoers
has only broken things thus far.
Got this answer elsewhere and worked for me:
First off you shouldn't need to sudo to run mysqldump. I assume that's the thing that's not working here - it's prompting for a password and failing. Remove that and this should work fine if everything else is set properly.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.