fstab
fstab

Reputation: 5039

exiting from php command without triggering shutdown functions

how can I exit from a php script (for example with the exit() function) but without triggering all previously registered shutdown functions (with register_shutdown_function)?

Thanks!

EDIT: alternatively, is there a way to clear from all the registered shutdown functions?

Upvotes: 2

Views: 1355

Answers (3)

Vitaly
Vitaly

Reputation: 71

From https://www.php.net/manual/en/function.register-shutdown-function.php

If you call exit() within one registered shutdown function, processing will stop completely and no other registered shutdown functions will be called.

Add a new handler to the very top of the code with the code:

exit();

Upvotes: 0

Mark Baker
Mark Baker

Reputation: 212512

Shutdown functions will not be executed if the process is killed with a SIGTERM or SIGKILL signal.

posix_kill(posix_getpid(), SIGTERM);

Upvotes: 7

Philipp
Philipp

Reputation: 15629

Don't use register_shutdown_function directly. Create a class which manage all shutdown functions and which has his own function and an enable property.

class Shutdown {

    private static $instance = false;
    private $functions;
    private $enabled = true;

    private function Shutdown() {
        register_shutdown_function(array($this, 'onShutdown'));
        $this->functions = array();
    }

    public static function instance() {
        if (self::$instance == false) {
            self::$instance = new self();
        }

        return self::$instance;
    }

    public function onShutdown() {
        if (!$this->enabled) {
            return;
        }

        foreach ($this->functions as $fnc) {
            $fnc();
        }
    }

    public function setEnabled($value) {
        $this->enabled = (bool)$value;
    }

    public function getEnabled() {
        return $this->enabled;
    }

    public function registerFunction(callable $fnc) {
        $this->functions[] = $fnc;
    }

}

Upvotes: 4

Related Questions