-2

How can I detect whether PHP is shutting down? By "shutting down", I mean that a function registered with register_shutdown_function is currently executing. For example, consider the following code:

<?php

function do_something() {
    // How can I detect whether PHP is shutting down.
}

register_shutdown_function('do_something');
do_something();

In the above code snippet, I want to be able to detect shutdown from within the do_something function.

Joshua Spence
  • 732
  • 1
  • 6
  • 19
  • 3
    What do you mean by "I want to detect[...]" ? If `do_something` is fired, that means PHP is already shuting down – Max Nov 28 '16 at 20:35
  • As @Max said, `register_shutdown_function()` is used to call a specific function after the script has completed or exited. Your `do_something()` function will be called when the script has completed. – Kitson88 Nov 28 '16 at 20:42
  • Ah sorrry, it looks like I stuffed up the code block. Let me fix it. – Joshua Spence Nov 28 '16 at 20:53
  • 2
    Possible duplicate of [How to determine that a PHP script is in termination phase?](http://stackoverflow.com/questions/6227611/how-to-determine-that-a-php-script-is-in-termination-phase) – HPierce Nov 28 '16 at 20:56

1 Answers1

0

This should work:

<?php

// receive true or false for knowing if register_shutdown_function() called this function
function do_something($is_register_shutdown_function = false) {
    // How can I detect whether PHP is shutting down.
    if($is_register_shutdown_function === true){
        file_put_contents('do_something.log', "do_something() - ".time().".".microtime(true)."\n", FILE_APPEND);
    }

    // do as you please going forward
}

register_shutdown_function('do_something', true); // pass true to the first parameter of do_something()
do_something();
MonkeyZeus
  • 20,375
  • 4
  • 36
  • 77