Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Checking exec() runs successfully or not

Tags:

php

exec

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"; ?> 
like image 510
soft genic Avatar asked Aug 09 '12 02:08

soft genic


People also ask

How do you know if an exec is successful?

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

How to check if exec failed?

If any of the exec() functions returns, an error will have occurred. The return value is -1, and errno will be set to indicate the error.

How do you check if exec is enabled in PHP?

php phpinfo(); ?> You can search for disable_functions and if exec is listed it means it is disabled. To enable it just remove the exec from the line and then you need to restart Apache and you will be good to go. If exec is not listed in the disable_functions line it means that it is enabled.

Does exec exit?

It is equivalent to the C library routine also called exit , or to returning from main . exec replaces the shell with a new executable image (still running in the same process), which will in due course exit and return some code or other to the parent process.


2 Answers

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

like image 198
Matt Williamson Avatar answered Sep 16 '22 20:09

Matt Williamson


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

like image 39
malhal Avatar answered Sep 20 '22 20:09

malhal