How to Create Daemons in PHP


Developers are using PHP to create websites or web applications but very few developers are creating desktop applications or command line tools using PHP. There is a class System_Deamon, which can be used to create Deamons using PHP.

What is a Daemon?

A daemon is a Linux program that run in the background, just like a ‘Service’ on Windows. It can perform all sorts of tasks that do not require direct user input. Apache is a daemon, so is MySQL. All you ever hear from them is found in somewhere in /var/log, yet they silently power over 40% of the Internet.

You reading this page, would not have been possible without them. So clearly: a daemon is a powerful thing, and can be bend to do a lot of different tasks.

Why PHP?

Most daemons are written in C. It’s fast & robust. But if you are in a LAMP oriented company like me, and you need to create a lot of software in PHP anyway, it makes sense:

  • Reuse & connect existing code: Think of database connections, classes that create customers from your CRM, etc.
  • Deliver new applications very fast: PHP has a lot of build in functions that speed up development greatly.
  • Everyone knows PHP (right?): If you work in a small company: chances are there are more PHP programmers than there are C programmers. What if your C developers leaves?

Possible use cases of Deamons

  • Website optimization: If you’re running a (large) website, jobs that do heavy lifting should be taken away from the user interface and scheduled to run on the machine separately.
  • Log parser: Continually scan logfiles and import critical messages in your database.
  • SMS daemon: Read a database queue, and let your little daemon interface with your SMS provider. If it fails, it can easily try again later!
  • Video converter (think Youtube): Scan a queue/directory for incoming video uploads. Make some system calls to ffmpeg to finally store them as Flash video files. Surely you don’t want to convert video files right after the upload, blocking the user interface that long? No: the daemon will send the uploader a mail when the conversion is done, and proceed with the next scheduled upload

Deamons vs Cronjobs

Some people use cronjobs for the same Possible use cases. Crontab is fine but it only allows you to run a PHP file every minute or so.

  • What if the previous run hasn’t finished yet? Overlap can seriously damage your data & cause siginificant load on your machines.
  • What if you can’t afford to waita minute for the cronjob to run? Maybe you need to trigger a process the moment a record is inserted?
  • What if you want to keep track of multiple ‘runs’ and store data in memory.
  • What if you need to keep your application listening (on a socket for example)

Cronjobs are a bit rude for this, they may spin out of control and don’t provide a framework for logging, etc. Creating a daemon would offer more elegance & possibilities. Let’s just say: there are very good reasons why a Linux OS isn’t composed entirely of Cronjobs 🙂

How it works internally

(Nerd alert!) When a daemon program is started, it fires up a second child process, detaches it, and then the parent process dies. This is called forking. Because the parent process dies, it will give the console back and it will look like nothing has happened. But wait: the child process is still running. Even if you close your terminal, the child continues to run in memory, until it either stops, crashes or is killed.

In PHP: forking can be achieved by using the Process Control Extensions. Getting a good grip on it, may take some studying though.


Because the Process Control Extensions’ documentation is a bit rough, I decided to figure it out once, and then wrap my knowledge and the required code inside a PEAR class called: System_Daemon. And so now you can just:

And that’s all there is to it. The code after that, will run in your server’s background. So next, if you create a while(true) loop around that code, the code will run indefinitely. Remember to build in a sleep(5) to ease up on system resources.

Features & Characteristics

Here’s a grab of System_Daemon’s features:

  • Daemonize any PHP-CLI script
  • Simple syntax
  • Driver based Operating System detection
  • Unix only
  • Additional features for Debian / Ubuntu based systems like:
  • Automatically generate startup files (init.d)
  • Support for PEAR’s Log package
  • Can run with PEAR (more elegance & functionality) or without PEAR (for standalone packages)
  • Default signal handlers, but optionally reroute signals to your own handlers.
  • Set options like max RAM usage


You could download the package from PEAR, or, if you have PEAR installed on your system: just run this from a console:

You can also update it using that last command.


Though I have quite some daemons set up this way, it’s officially still 0.5.0-alpha. So please report any bugs over at the PEAR page. Other comments may be posted here.

Complex Example

Ready to dig a little deeper? This example program is called ‘logparser’, it takes a look at a more complex use of System_Daemon. For instance, it introduces command line arguments like:

Read this source to get the picture. Don’t forget the comments!

Console action: Controlling the Daemon

Now that we’ve created an example daemon, it’s time to fire it up! I’m going to assume the name of your daemon is logparser. This can be changed with the statement: System_Daemon::setOption(“appName”, “logparser”). But the name of the daemon is very important because it is also used in filenames (like the logfile).


Just make your daemon script executable, and then execute it:


Your daemon has no way of communicating through your console, so check for messages in:

And see if it’s still running:


Without the start/stop files (see below for howto), you need to:

Autch.. Let’s work on those start / stop files, right?

Start / Stop files (Debian & Ubuntu only)

Real daemons have an init.d file. Remember you can restart Apache with the following statement?

That’s a lot better than killing. So you should be able to control your own daemon like this as well:

Well with System_Daemon you can write autostartup files using the writeAutoRun() method, look:

$path = System_Daemon::writeAutoRun();

On success, this will return the path to the autostartup file: /etc/init.d/logparser, and you’re good to go!

Run on boot

Surely you want your daemon to run at system boot.. So on Debian & Ubuntu you could type:

Done your daemon now starts every time your server boots. Cancel it with:


Here are some issues you may encounter down the road.

  • Connect to MySQL after you start() the daemon.
    Otherwise only the parent process will have a MySQL connection, and since that dies.. It’s lost and you will get a ‘MySQL has gone away’ error.
  • Errors handling
    Good error handling is imperative. Daemons are often mission critical applications and you don’t want an uncatched error to bring it to it’s knees.

    • Reconnect to MySQL
      A connection may be interrupted. Think about network downtime or lock-ups when your database server makes backups. Whatever the cause: You don’t want your daemon to die for this, let it try again later.
    • Write your own php error handler
      It should forward all the PHP errors to the log() method, so they end up in your logfile. Otherwise it’s very hard to spot errors, since the daemon has no way of writing to your console anymore!
  • Monit
    Monit is a standalone program that can kickstart any daemon, based on your parameters. Should your daemon fail, monit will mail you and try to restart it.

Should your daemon fail, monit will mail you and try to restart it.

I know I’m saying MySQL a lot, but you can obviously replace that with Oracle, MSSQL, PostgreSQL, etc.
Originally posted by: Kevin van Zonneveld

If you’ve got any thoughts, comments or suggestions for things we could add, leave a comment! Also please Subscribe to our RSS for latest tips, tricks and examples on cutting edge stuff.

0 I like it
0 I don't like it