Saturday, June 6th, 2009

Daemonize PHP script

If you need to run a PHP script continuously in the background, try pear package System_Daemon.

You can get it using pear install command or download it. Then code your script like following:


#!/usr/bin/php -q
<?php
require_once 'System/Daemon.php';
System_Daemon::setOption('appName', 'my_script_name');
System_Daemon::setOption('authorEmail', 'me@example.com');
System_Daemon::start();
/*
Rest of your code goes here.
*/

// Stop daemon.
if(some_condition())
{
	System_Daemon::stop();
}
?>

Chmod to make it executable and execute it as root/admin user:

chmod 755 /path/to/your/script.php

sudo /path/to/your/script.php