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).
- I have attempted giving the directory where the file is created (or the .php script which contains either of these exec commands) to apache with the
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.