我有一个PHP脚本,它被传递给远程服务器的MySQL连接细节,我希望它执行一个mysqldump命令。为此,我使用了php exec()函数:
<?php
exec("/usr/bin/mysqldump -u mysql-user -h 123.145.167.189 -pmysql-pass database_name > /path-to-export/file.sql", $output);
?>当正确的登录细节被传递给它时,它将非常好地工作。但是,我在检查它是否按预期执行,以及它是否没有找到为什么不执行时遇到了问题。$output数组返回为空,而如果我直接在命令行上运行命令,则会打印一条消息,告诉我登录失败。我想捕获这样的错误消息并显示它们。对怎么做有什么想法吗?
发布于 2012-07-26 23:13:10
您应该检查exec函数的第三个参数:&$return_var。
$return_var = NULL;
$output = NULL;
$command = "/usr/bin/mysqldump -u mysql-user -h 123.145.167.189 -pmysql-pass database_name > /path-to-export/file.sql";
exec($command, $output, $return_var);按照Unix中的约定,当发生问题时,进程返回除0以外的任何内容,。
所以你可以:
if($return_var) { /* there was an error code: $return_var, see the $output */ }发布于 2016-10-13 10:12:54
我找到的解决方案是在子shell中运行该命令,然后将stderr输出到stdout (2>&1)。这样,$output变量就会被错误消息填充(如果有的话)。
即:
exec("(mysqldump -uroot -p123456 my_database table_name > /path/to/dump.sql) 2>&1", $output, $exit_status);
var_dump($exit_status); // (int) The exit status of the command (0 for success, > 0 for errors)
echo "<br />";
var_dump($output); // (array) If exit status != 0 this will handle the error message. 结果:
int(6) 数组(1){ =>字符串(46) "mysqldump:未能找到表:"table_name"“}
希望能帮上忙!
发布于 2012-07-26 23:12:12
因为这一行重定向了stdout输出> /path-to-export/file.sql,
<?php
exec("/usr/bin/mysqldump -u mysql-user -h 123.145.167.189 -pmysql-pass database_name", $output);
/* $output will have sql backup, then save file with these codes */
$h=fopen("/path-to-export/file.sql", "w+");
fputs($h, $output);
fclose($h);
?> https://stackoverflow.com/questions/11679275
复制相似问题