46

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

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

5 回答 5

72

根据 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找到代码

于 2012-08-09T02:20:23.893 回答
15

正确的方法是检查 $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 初始化为零

于 2016-03-24T21:07:47.903 回答
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 的情况下。( 一 )

----------------
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

如果成功(零)

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
于 2012-08-09T02:24:24.640 回答
0

我为我工作

对于系统 linux 和 lang:php,laravel

exec('/usr/bin/tesseract 2.png out1 -l '.$lang,$output,$error);
           return (!$error)? "success":"Error";
于 2020-11-19T16:11:56.140 回答
0

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

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";
}
于 2021-02-18T13:12:42.103 回答