itsols
itsols

Reputation: 5582

php exec does not work as expected

My system: Ubuntu 11.10, LAMP Stack.

Issue:

I run the following in terminal and it does the back up correctly.

mysqldump -u root  dbBugTracker > BAK/dbw.sql

But I include it in my php code like the following and it does NOT work.

exec('/usr/bin/mysqldump -u root  dbTracker > BAK/dbT.sql');

Tips:

I appreciate any inputs on this. Thank!

MORE INFO: I added 2>&1 to the exec line and NOW the file contains some text but NOT the DB dump. This is an error and I have no idea how to deal with this :( Here's the error

mysqldump: Got error: 1045: Access denied for user 'root'@'localhost' (using password: NO) when trying to connect So this is what the output file (dbw.sql) now contains. Once again, it works fine when I run the dump from terminal.

Upvotes: 1

Views: 2221

Answers (3)

Matthew Blancarte
Matthew Blancarte

Reputation: 8301

You're running that dump command as a different user while on the command line. You are running it as Apache (I assume) when using exec(). Try adding a password parameter to the exec command, or creating an php-specific user in your db with appropriate privileges.

UPDATE:: As I guessed, you are not able to use the root user while executing this dump using PHP. So, create a new user.

First, login to your database from the command line. If you are the root user, don't bother with using -u root:

mysql

Now that you're logged in, go ahead and create a new user for Apache to use:

GRANT ALL ON database_name.* TO yourapacheuser@localhost IDENTIFIED BY 'yourpassword';

Go ahead and logout of mysql:

exit

Next, let's re-work your original code a bit...

$db_user = 'newusername';
$db_pass = 'pass';

$command = "mysqldump --add-drop-table -u $db_user -p$db_pass database_name > backup.file.sql";
$output = `$command`;
echo "Your database has now been backed up.";

Now, to execute the file, run this from the command line:

php path/to/sqldumpfile.php

Hopefully you can adapt this pseudo-code. Best of luck!

Upvotes: 3

Camden S.
Camden S.

Reputation: 2245

First, you should get it working on the command line. Verify that this produces the desired results prior to using PHP's exec():

/usr/bin/mysqldump -u root -p YOUR_PASSWORD dbTracker > BAK/dbT.sql

If it DOES work, then it's an issue somewhere in your PHP config.

The first thing to check is safe_mode. Are you using safe_mode? What version of PHP are you running?

Another possibility may be that your PHP user does not have permission to use the mysqldump binary.

Upvotes: 0

Roman Newaza
Roman Newaza

Reputation: 11690

How do you print it? Debug it like this:

<?php

exec('/usr/bin/mysqldump -u root  dbTracker > BAK/dbT.sql', $output);

var_dump($output);

Upvotes: 0

Related Questions