如何知道php运行成功与否的代码

时间:2013-08-07 13:51:53

标签: php

我有以下代码

<html>
<body>
<?php
if ($_GET['run']) {
  # This code will run if ?run=true is set.
 echo "Hello";
  exec ("chmod a+x ps.sh");

  exec ("sh ps.sh");
}
?>

<!-- This link will add ?run=true to your URL, myfilename.php?run=true -->
<a href="?run=true">Click Me!</a>

现在我想知道exec ("chmod a+x ps.sh")是否正常执行。我该怎么办?

3 个答案:

答案 0 :(得分:1)

查看the documentation

string exec ( string $command [, array &$output [, int &$return_var ]] )

...

return_var
     

如果return_var参数与输出参数一起出现,   然后执行命令的返回状态将写入此   变量

所以只需检查返回码是否不等于零:

exec ("chmod a+x ps.sh", $output, $return);
if ($return != 0) {
    // An error occured, fallback or whatever
    ...
}

答案 1 :(得分:0)

exec(..., $output, $return);

if ($return != 0) {
    // something went wrong
}

通过为第三个参数提供变量名来捕获返回代码。如果该变量之后包含0,那么一切都很好。如果它不是0,那就出错了。

答案 2 :(得分:0)

exec()接受其他参数。第二个是输出,它允许您查看命令的输出。

在chmod的情况下,正确的输出是没有的。

exec()的第三个参数是返回状态。如果成功,它应为0。

然后您应该执行以下操作:

exec ("chmod a+x ps.sh", $out, $value);

if(!empty($out) || $value != 0)
{
    #there was an error
}

注意:您不必事先初始化$ out或$ value,PHP会在您使用它们时创建它们。