1

Unfortunately calling php exit() on php-fpm/nginx configuration does not stop the script immediately while file handles might not be closed.

Some developers suggest calling fastcgi_finish_request() but also this does not stop the script.

Others suggest wrapping all code in a catch block:

<?php
    class SystemExit extends Exception {}
    try {
       /* PUT ALL THE CODE HERE */
    } catch (SystemExit $e) { /* do nothing */ }
?>

and throwing an exception where code stop is needed:

if (SOME_EXIT_CONDITION)
   throw new SystemExit(); // instead of exit()

This would mean editing all php files to include try/catch block and seems tedious to me.

Are there any other clean solutions?

2
  • 1
    exit works for me. What exactly happens in your case? Commented Nov 27, 2015 at 10:43
  • try the following code: ` echo "You have to wait 10 seconds to see this.<br>"; register_shutdown_function('shutdown'); exit; function shutdown(){ sleep(10); echo "Because exit() doesn't terminate php-fpm calls immediately.<br>"; } ` Commented Nov 27, 2015 at 10:55

1 Answer 1

1

So we found out that it's a register_shutdown_function callback that prevents your script from exiting immediately.

PHP shutdown function is designed to be called on any script shutdown when possible. But it has a feature: if one of shutdown callbacks calls exit — script is exiting without calling any other callbacks.

So if you really want to skip a shutdown function in some cases, you should register some killer-function as a very first shutdown callback. Inside that killer-function you will check a kind of singleton for state: do we want to exit? — call exit(), otherwise — return.

<?php

function killer_function() {
    if ($someGlobalThing->needToExitRightNow()) {
        exit();
    }
}

register_shutdown_function('killer_function');

// ...

function exit_now() {
    $someGlobalThing->exitNow();
    exit();
}

($someGlobalThing can be a singleton or some super-global variable or a global registry or whatever you like)

Then calling exit_now() will do the trick.

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

Comments

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.