Is there a way to detect if a running built-in PHP server has been stopped? Either by hitting Ctrl-C
or just by closing the terminal window.
I'm using it for a development environment and would like to clean up some files on teardown.
well, i don't know if there are exist in the php built-in server feature to do so,
but as a work around you may accomplish this using terminal,
using the ;
symbol which is used to separate two commands and in executing the second command after the first command finishes it's execution.
for example this script will add shut down line to the file status.txt only when you hit CTRL+C
-finishing the first command- :
php -S localhost:8000 ; echo "shut down" >> status.txt
you may create a new php/bash script or whatever to execute specific tasks and execute it after exiting the server -after hitting CTRL+C
You could register function which will be called on script exit by register_shutdown_function()
register_shutdown_function(function() {/* Some cleanup activity */});
More sophisticated solution is to grab signal by pcntl_signal()
. The one from ctrl + c is SIGINT
pcntl_signal(SIGINT, "signalHandler");
function signalHandler($signal) {
switch($signal) {
case SIGINT:
print "Caught SIGINT
";
exit;
}
}