I have a php script that runs in the background 24/7. I have to occasionally terminate it, and the point of the script is to cache transaction data to memcahced from bitcoin RPC (if you don't know what that is, it is irrelevant). I want the script to execute a function when the program receives the signal sent on ^C (control C).
There are two variables you can use while writing command line applications with PHP: $argc and $argv. The first is the number of arguments plus one (the name of the script running). The second is an array containing the arguments, starting with the script name as number zero ($argv[0]).
The CLI SAPI differs from other PHP SAPIs and these differences are documented in PHP Command Line Usage: Differences to other SAPIs. PHP is not just for web pages and web sites anymore. It can be used for command line scripting as well.
To pass command line arguments to the script, we simply put them right after the script name like so... Note that the 0th argument is the name of the PHP script that is run. The rest of the array are the values passed in on the command line. The values are accessed via the $argv array.
PHP's Command Line Interface (CLI) allows you to execute PHP scripts when logged in to your server through SSH. ServerPilot installs multiple versions of PHP on your server so there are multiple PHP executables available to run. You can also configure the PHP version used when you call just the command php.
You probably want pcntl_signal
. The signal you need to catch is SIGINT
.
In case anybody else is looking, I've found an answer that doesn't require pcntl_signal.
You can use system("stty intr ^-");
to stop ^C
from exiting the script automatically. You can then capture it as ord(fread(STDIN, 1)) == 3
within PHP, and handle exiting manually.
I'm working on a library that does this.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With