sapi_windows_set_ctrl_handler()

sapi_windows_set_ctrl_handler() — Set or remove a CTRL event handler.

Built-in function of PHP 8.5. The manual lists it as available in PHP 7 >= 7.4.0, PHP 8. This page is the reference card: signature, parameters and return value, plus the changelog and the example the manual provides.

What it does

Sets or removes a CTRL event handler, which allows Windows CLI processes to intercept or ignore CTRL+C and CTRL+BREAK events. Note that in multithreaded environments, this is only possible when called from the main thread.

Signature

sapi_windows_set_ctrl_handler(?callable $handler, bool $add = true): bool handler(int $event): void

Parameters

ParameterTypeWhat it takes
$handler?callableA callback function to set or remove. If set, this function will be called whenever a CTRL +C or CTRL +BREAK event occurs. The function is supposed to have the following signature: function handler(int $event): void event The CTRL event which has been received; either PHP_WINDOWS_EVENT_CTRL_C or PHP_WINDOWS_EVENT_CTRL_BREAK. Setting a null handler causes the process to ignore CTRL +C events, but not CTRL +BREAK ...
$addboolIf true, the handler is set. If false, the handler is removed.

Return value

Returns true on success or false on failure.

Example

A runnable snippet:

function ctrl_handler(int $event) { switch ($event) { case PHP_WINDOWS_EVENT_CTRL_C: echo "You have pressed CTRL+C\n"; break; case PHP_WINDOWS_EVENT_CTRL_BREAK: echo "You have pressed CTRL+BREAK\n"; break; } } sapi_windows_set_ctrl_handler('ctrl_handler'); while (true); // infinite loop, so the handler can be triggered

See also

sapi_windows_generate_ctrl_event()

All PHP 8.5 built-in functions

Reference card built from the PHP manual page sapi_windows_set_ctrl_handler() (PHP documentation, CC BY 3.0). The page is generated from the manual, so the wording of the parameter and return value text follows php.net.