17th
Persistent Background PHP Scripts on Shared Hosting Platforms
I find myself sometimes wanting to keep a php script running in the background may be so it can poll a database or provide some kind of service daemon. Sometimes, this script might be hosted on a shared hosting platform and I don’t have the ability to configure the script to run at system startup. The solution to this problem might be to create a cron entry to run the script. The problem with this method is that in scenarios where you want only a copy of the script to remain active, having cron run every now and then to start the script up will only lead to having many copies of the same script running.
I initally thought about using a file where I write the process id of the script as it is spawned. To prevent having multiple copies of the script running, the script will first check the pid file and attempt to signal the process having the pid in the file. If the process responds in a particular way that’s unique to the script, we assume that the script is running and then terminate the other copy. The problem with this approach is that it wouldn’t work on a Windows host.
I came up with another alternative. This method involves the use of file locks. When the script is bring run for the first time, it obtains a lock on a file and keeps this lock for the lifetime of the script. Any additional copies of this script will attempt to obtain a lock on the same file. Provided there’s a copy of the script still running, the file lock will fail. This will signal the script to terminate since a copy is already running.
Here’s the snippet:
<?php
set_time_limit(0);
$fh = fopen(".lock", "w");
if (!flock($fh, LOCK_EX | LOCK_NB)) exit;
// Perform script operations
flock($fh, LOCK_UN);
fclose($fh);
?>