Checking exec() runs successfully or not

I have been trying to let know know if the exec() command in php executes successfully or not so i can echo certain messages accordingly. I tried the following piece of code but the problem with it is that whether exec() runs successfully or not it always echo "PDF not created" and never echo pdf created successfully. Kindly let me know how can i perform the check on the execution of exec() so i can echo messages accordingly Thanks,

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

Solution 1:

According to PHP's exec quickref, you can pass pointers in to get the output and status of the command.

<?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";
}
?>

If you want to enumerate the possible errors, you can find the codes over at hiteksoftware

Solution 2:

The correct way is to check that the $return_var was not set to zero because it is only set to zero when it is successful. In certain cases the exec can fail and the return_var is not set to anything. E.g. if the server ran out of disk space during the 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";
}

?>

Note : do not initialize $return_var to zero

Solution 3:

A simple sample:

$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 );

In case of not ping or 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

In case of success ( 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