0

Heyas,

So this simple exec() script runs fine for the first two times, in trying to generate a PDF file from a webpage (using wkhtmltopdf). It first) deletes the existing file, and second) creates the new PDF file in its place. If I run the script a second time, it deletes the file again, and then creates a new one, as expected. However, if I run it one more time, it deletes the files, creates a new one, but then the script seems to hang until the 30-second 504 timeout error is given. The script, when it works, only takes about 3 seconds to run/return. It also kills the entire server (any other local PHP sites no longer work). If I restart the PHP server, everything still hangs (with no success). Interestingly, if I run the script once, and then restart the PHP server, I can keep doing this without issue (but only generating the PDF up to two times). No PHP errors are logged. Why would it be stalling out subsequent times?

    $filePath = 'C:\\wtserver\\tmp\\order_' . $orderId . '.pdf';

    // delete an existing file
    if(file_exists($filePath)) {
        if(!unlink($filePath)) {
            echo 'Error deleting existing file: ' . $filePath;
            return;
        }
    }

    // generates PDF file at C:\wtserver\tmp\order_ID.pdf
    exec('wkhtmltopdf http://google.com ' . $filePath);

I've tried a simple loop to check for the script's completion (successful output), and then try to exit, but it still hangs:

    while(true) {
        if(file_exists($filePath)) {
            echo 'exit';
            exit(); // have also tried die()
            break;
        }
        //todo: add time check/don't hang
    }

If I can't figure this bit out, for now, is there a way to kill the exec script, wrapping it somehow? The PDF is still generated, so the script is working, but I need to kill it and return a response to the user.

Solution:

Have to redirect standard output AND standard error, to end the process immediately, ie. in Windows:

exec('wkhtmltopdf http://google.com ' . $filePath . ' > NUL 2> NUL');
1
  • where did you tried the simple check .your exec call is blocking. so just wondering were probably your while loop is running. Commented Jul 14, 2016 at 7:20

1 Answer 1

1

do you know that you can run the executable in background, like this

exec($cmd . " > /dev/null &");

This way you can immediately come out of it.

Sign up to request clarification or add additional context in comments.

2 Comments

That sounded really promising, but I tried it, and it's still hanging in the same way :( Thanks though...
Oh I think we got it! Looks like I also had to redirect the standard error as well as the standard output, ie. (check solution above). Thank you!!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.