2011-05-08 21:12
浏览 41


Before you say there are other questions like this, but none of the answers I've seen worked, so I'm making a fresh question.

I'm trying to use mysqldump via system() with this command:

$backup_path = $_SERVER['DOCUMENT_ROOT'] . '/website/acp/backup/';
$backup_name = $backup_path . $dbname . '.backup.' . date('l.dS.F.Y.g.iA') . '.sql';

$command = 'mysqldump ' . $dbname . ' -u ' . $dbuser . ' -p' . $dbpasswd . ' > ' . $backup_name;

system($command, $returned);


$returned outputs 127 and a blank file with a size of zero KB is located in the backup folder, now when I echo $command and then enter it into Terminal, it works perfectly and generates a full backup of the database. This is the part I don't understand, why is it not working well in the system() call but in Terminal it works just fine?

  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 邀请回答

3条回答 默认 最新

  • duanshan1977
    duanshan1977 2011-05-08 21:24

    This is because when running mysqldump you are required to enter the password, even if you specify it with -p

    This should be helpful :

    点赞 评论
  • duanguoping2016
    duanguoping2016 2011-05-08 21:30

    Your problem could well be that you don't have permission to write to the backups directory.

    If you run the code:

    $backup_path = $_SERVER['DOCUMENT_ROOT'] . '/website/acp/backup/';
    file_put_contents("{$backup_path}test-file.txt", "test data");

    Does a file appear in the backup directory?

    If not you need to modify the permissions of the directory so that the webserver user can write to it. chmod 777 is the easy solution but will leave the permissions wide open.

    点赞 评论
  • dpjjmo3079
    dpjjmo3079 2013-10-15 01:48

    I have to disagree with Andrei's answer above.

    The following works on a number of shared hosting companies:

    $command = 'mysqldump --opt --host='.$host.' --user='.$mysql_username.' --password=\''.$mysql_password.'\' '.$dbname.' > \''.$filename.'\'';

    Careful if you have white space anywhere in your arguments (file names, passwords, etc) that you use quotes. In PHP you might need to use back slashes, like I did above, when quoting. Preceeding or trailing spaces are usually a bad idea, but I've encountered a client where this turned out to be the reason for an empty, 0 bytes mysqldump file. Quoting fixed the problem. You might also need to shell escape the arguments.

    The following two lines are quite different:

    -password='password  ' db_name > 'my file.sql'
    -password=password   db_name > my file.sql

    Note that the second one also has two spaces at the end of the password, but even HTML may ignore it.

    I should probably mention for the noobs... make sure you can manually connect with the settings before looking for reasons it is not working, e.g. - make sure the host is correct, e.g. localhost or - make sure the username and password work

    点赞 评论