我一直试图让我们知道exec()
php中的命令是否成功执行,所以我可以相应地回复某些消息.我尝试了下面这段代码,但问题是无论是否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";
?>
Run Code Online (Sandbox Code Playgroud)
Mat*_*son 60
根据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";
}
?>
Run Code Online (Sandbox Code Playgroud)
如果要枚举可能的错误,可以在hiteksoftware上找到代码
mal*_*hal 14
正确的方法是检查$ return_var是否未设置为零,因为它仅在成功时设置为零.在某些情况下,exec可能会失败,return_var也不会设置为任何内容.例如,如果服务器在exec期间耗尽了磁盘空间.
<?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";
}
?>
Run Code Online (Sandbox Code Playgroud)
注意:不要将$ return_var初始化为零
一个简单的示例:
$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 );
Run Code Online (Sandbox Code Playgroud)
如果未 ping 通或出现错误。( 一 )
----------------
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
Run Code Online (Sandbox Code Playgroud)
如果成功(零)
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
Run Code Online (Sandbox Code Playgroud)