检查exec()是否成功运行

时间:2012-08-09 02:08:45

标签: php exec

我一直试图让我们知道php中的exec()命令是否成功执行,因此我可以相应地回显某些消息。 我尝试了下面这段代码,但问题是exec()是否成功运行它总是echo "PDF not created"并且永远不会成功地回显pdf。请告诉我如何执行exec()执行检查,以便我可以相应地回复消息 谢谢,

<?php
if (exec('C://abc//wkhtmltopdf home.html sample.pdf'))
echo "PDF Created Successfully";
else
echo "PDF not created";
?>

5 个答案:

答案 0 :(得分:58)

根据PHP的exec quickref,您可以传入指针以获取命令的输出和状态。

<?php
exec('C://abc//wkhtmltopdf home.html sample.pdf', $output, $return);

// Return will return non-zero upon an error
if (!$return) {
    echo "PDF Created Successfully";
} else {
    echo "PDF not created";
}
?>

如果您想列举可能的错误,可以在hiteksoftware找到代码

答案 1 :(得分:12)

正确的方法是检查$ return_var是否未设置为零,因为它仅在成功时设置为零。在某些情况下,exec可能会失败,return_var也不会设置为任何内容。例如。如果服务器在执行期间用尽了磁盘空间。

<?php
exec('C://abc//wkhtmltopdf home.html sample.pdf', $output, $return_var);
if($return_var !== 0){ // exec is successful only if the $return_var was set to 0. !== means equal and identical, that is it is an integer and it also is zero.
    echo "PDF not created";
}
else{
    echo "PDF Created Successfully";
}

?>

注意:不要将$ return_var初始化为零

答案 2 :(得分:4)

一个简单的样本:

$ip = "192.168.0.2";
$exec = exec( "ping -c 3 -s 64 -t 64 ".$ip, $output, $return );
echo $exec;
echo "<br />----------------<br />";
print_r( $output );
echo "<br />----------------<br />";
print_r( $return );

如果没有ping或ERROR。 (ONE)

----------------
Array ( [0] => PING 192.168.0.2 (192.168.0.2) 64(92) bytes of data. [1] => [2] => --- 192.168.0.2 ping statistics --- [3] => 3 packets transmitted, 0 received, 100% packet loss, time 2016ms [4] => )
----------------
1

如果成功(ZERO)

rtt min/avg/max/mdev = 4.727/18.262/35.896/13.050 ms
----------------
Array ( [0] => PING 192.168.0.2 (192.168.0.2) 64(92) bytes of data. [1] => 72 bytes from 192.168.0.2: icmp_req=1 ttl=63 time=14.1 ms [2] => 72 bytes from 192.168.0.2: icmp_req=2 ttl=63 time=35.8 ms [3] => 72 bytes from 192.168.0.2: icmp_req=3 ttl=63 time=4.72 ms [4] => [5] => --- 192.168.0.2 ping statistics --- [6] => 3 packets transmitted, 3 received, 0% packet loss, time 2003ms [7] => rtt min/avg/max/mdev = 4.727/18.262/35.896/13.050 ms )
----------------
0

答案 3 :(得分:0)

我为我工作

用于系统linux和lang:php,laravel

exec('/usr/bin/tesseract 2.png out1 -l '.$lang,$output,$error);
           return (!$error)? "success":"Error";

答案 4 :(得分:0)

如果您不关心返回码,我建议您使用 next 方法:

private function execCommand($command) {
    exec($command, $output, $return);

    return $return === 0;
}

然后简单地调用它:

if ($this->execCommand("C://abc//wkhtmltopdf home.html sample.pdf")) {
    echo "Success";
} else {
    echo "Error";
}