PHP Function Reference

PHP sapi_windows_set_ctrl_handler() Function



The PHP sapi_windows_set_ctrl_handler() function 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.

Syntax

sapi_windows_set_ctrl_handler(handler, add)

Parameters

event

Required. Specify a 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:

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 events.
add Optional. If true, the handler is set. If false, the handler is removed. Default is true.

Return Value

Returns true on success or false on failure.

Example: basic sapi_windows_set_ctrl_handler() usage

The example below shows how to pass along CTRL+BREAK events to a child process. In this case the child process echoes "Hello World!" every second, until the user presses CTRL+BREAK, what causes only the child process to be terminated.

<?php
//forwarding CTRL+BREAK events to the child process
sapi_windows_set_ctrl_handler('sapi_windows_generate_ctrl_event');

//creating a child process which echoes every second
$cmd = ['php', '-r', 'while (true) { echo "Hello World!\n"; sleep(1); }'];
$descspec = array(['pipe', 'r'], ['pipe', 'w'], ['pipe', 'w']);
$options = ['create_process_group' => true];
$proc = proc_open($cmd, $descspec, $pipes, null, null, $options);
while (true) {
  echo fgets($pipes[1]);
}
?>

Example: sapi_windows_set_ctrl_handler() example

The example below shows how to intercept CTRL events.

<?php
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');

//infinite loop, so the handler can be triggered
while (true); 
?>

❮ PHP Miscellaneous Reference