Welcome to a quick tutorial and example of how to create a PHP daemon. Need to run a “service” PHP script in the background? Send out emails, fetch updates, or monitor something?
- PHP does not support daemons natively.
- But we can simulate a daemon by creating a script that runs infinitely –
while (true) { /* DO SOMETHING */ sleep(1); }
- Then set it to run in the command line –
PHP DAEMON.PHP
Yes, it’s that simple. Let us walk through a few more examples in this guide – Read on!
ⓘ I have included a zip file with all the example source code at the start of this tutorial, so you don’t have to copy-paste everything… Or if you just want to dive straight in.
TABLE OF CONTENTS
DOWNLOAD & NOTES
Firstly, here is the download link to the example code as promised.
QUICK NOTES
If you spot a bug, feel free to comment below. I try to answer short questions too, but it is one person versus the entire world… If you need answers urgently, please check out my list of websites to get help with programming.
EXAMPLE CODE DOWNLOAD
Click here to download the source code, I have released it under the MIT license, so feel free to build on top of it or use it in your own project.
SIMPLE DAEMON EXAMPLES
All right, let us now get into the simple examples of PHP daemons.
EXAMPLE 1) BASIC MECHANICS
<?php
// (A) COMMAND LINE ONLY!
if (isset($_SERVER["REMOTE_ADDR"]) || isset($_SERVER["HTTP_USER_AGENT"]) || !isset($_SERVER["argv"])) {
exit("Please run this script from command line");
}
// (B) SETTINGS
$cycle = 10; // WAIT 10 SECS BETWEEN CYCLES
// (C) RUN
while (true) {
echo "It works!" . PHP_EOL;
sleep($cycle);
}
Yep, that’s all for the “basics” of a “daemon” in PHP. Just run this script in the command line PHP 1-basic.php
, and it will output It works!
every 10 seconds… Not very useful, so let’s go through more practical examples below.
EXAMPLE 2) FETCH DATA FROM API
<?php
// (A) COMMAND LINE ONLY!
if (isset($_SERVER["REMOTE_ADDR"]) || isset($_SERVER["HTTP_USER_AGENT"]) || !isset($_SERVER["argv"])) {
exit("Please run this script from command line");
}
// (B) SETTINGS
$cycle = 10; // WAIT 10 SECS BETWEEN CYCLES
$url = "http://localhost/2b-dummy.txt"; // DUMMY SERVER
// (C) RUN
while (true) {
// (C1) CURL INIT
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
// (C2) FETCH UPDATES FROM DUMMY SERVER
$result = curl_exec($ch);
if (curl_errno($ch)) { echo curl_error($ch) . PHP_EOL; }
else { echo $result . PHP_EOL; }
curl_close($ch);
// (C3) UPDATE DATABASE
$result = json_decode($result, true);
// $sql = "UPDATE `rates` SET `EUR` = ?";
// $sql = "UPDATE `rates` SET `GBP` = ?";
unset($result);
// (C4) WAIT FOR NEXT CYCLE
sleep($cycle);
}
{"EUR":1.17,"GBP":1.38}
Let’s say that we have an e-commerce or trading website that deals with multiple currencies. So in this one, we periodically:
- Use CURL to fetch the latest exchange rate for EUR-USD and GBP-USD.
- Then update the rates in the local database.
EXAMPLE 3) MONITOR SERVER
<?php
// (A) COMMAND LINE ONLY!
if (isset($_SERVER["REMOTE_ADDR"]) || isset($_SERVER["HTTP_USER_AGENT"]) || !isset($_SERVER["argv"])) {
exit("Please run this script from command line");
}
// (B) SETTINGS
$url = "http://localhost";
$log = "stats.txt";
$cycle = 10; // WAIT 10 SECS BETWEEN CYCLES
// (C) INIT LOG FILE
file_put_contents($log, "");
// (D) RUN MONITOR
while (true) {
// (D1) CURL TEST FETCH
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$result = curl_exec($ch);
// (D2) ERROR
if (curl_errno($ch)) {
$line = sprintf("%s %s\r\n",
date("Y-m-d H:i:s"), curl_error($ch)
);
}
// (D3) OK
else {
$info = curl_getinfo($ch);
$line = sprintf("%s %s\r\n",
date("Y-m-d H:i:s"), $info["http_code"], $info["total_time_us"]
);
}
curl_close($ch);
// (D4) RECORD
file_put_contents($log, $line, FILE_APPEND);
// (D5) NEXT CYCLE
sleep($cycle);
}
Need to monitor the performance or uptime of a server? Use this script… Although a text file is not the best, recording the stats in a database will be a better idea.
USEFUL BITS & LINKS
That’s all for this tutorial, and here is a small section on some extras and links that may be useful to you.
LIMITATIONS
As you may have already guessed, this method will permanently take up one process thread. While some people may flip out at the idea of an infinite loop, but it works – It is at least good for the people who don’t have access to install a PHP extension on the server. Most importantly, it is very easy to implement.
RUN AT STARTUP
It will be a pain to manually run the script every time, so here is how we schedule it to run at startup instead:
LINKS & REFERENCES
- PHP Daemon with pcntl extension
- PHP Daemon on GitHub
- Run PHP Script In Background – Code Boxx
- Schedule PHP Script – Code Boxx
INFOGRAPHIC CHEAT SHEET

THE END
Thank you for reading, and we have come to the end of this guide. I hope that it has helped you with your project, and if you want to share anything with this guide, please feel free to comment below. Good luck and happy coding!
If we close command line tool, php process will be terminate.
Is there any solution for thаt?
I can’t remember the exact steps and commands, but basically, run the PHP like a background process. In Linux, it goes something like
nohup php SCRIPT.php > /dev/null
. As for Windows, I remember using PHP to spawn another “silent command”, something likepclose(popen('start /B php.exe SCRIPT.php));
.If you’re on Linux I highly recommend that you use supervisor. I don’t know any similar tools for Windows or Mac.
I do remember getting supervisor to run on Leopard (?) before. Not so sure about the current versions though…