Run a PHP script as a daemon
Below is a simple example of a PHP script and guidance on how you could run it as a daemon.
Example PHP Script
Create a file called daemon_example.php
:
#!/usr/bin/php
<?php
// This script simply writes a timestamp to a log file every 10 seconds.
$logFile = '/tmp/mydaemon.log';
while (true) {
$timestamp = date('Y-m-d H:i:s');
file_put_contents($logFile, "Current time: $timestamp\n", FILE_APPEND);
sleep(10);
}
Key Points About the Script:
- It runs an infinite loop.
- Every 10 seconds, it appends the current time to the file
/tmp/mydaemon.log
. - The
#!/usr/bin/php
shebang line ensures it can be run directly (if the file is executable).
Making the Script Executable
In a terminal, run:
chmod +x daemon_example.php
Now you can run the script directly:
./daemon_example.php
This will start running in the current terminal. To stop it, press Ctrl+C
.
Running it as a Daemon
Method 1: Using nohup
and &
The simplest way to run it as a daemon (background process) is:
nohup ./daemon_example.php > /dev/null 2>&1 &
nohup
ensures the process isn’t stopped when you log out.> /dev/null 2>&1
discards any output to avoid cluttering the terminal.- The
&
at the end runs it in the background.
You can check if it’s running using:
ps aux | grep daemon_example.php
To stop it, find its process ID (PID) and kill it:
kill <PID>
Method 2: Using systemd
(Preferred for Production)
If you have root or administrative access and your system uses systemd
, you can create a service file to manage your PHP script as a proper daemon.
-
Create a service file (e.g.,
/etc/systemd/system/mydaemon.service
):[Unit] Description=My PHP Daemon Service [Service] ExecStart=/usr/bin/php /path/to/daemon_example.php Restart=always [Install] WantedBy=multi-user.target
-
Reload systemd’s configuration:
sudo systemctl daemon-reload
-
Start the service:
sudo systemctl start mydaemon.service
-
Enable the service on startup:
sudo systemctl enable mydaemon.service
Check the status:
sudo systemctl status mydaemon.service
Stop the service:
sudo systemctl stop mydaemon.service
Using systemd
provides a more robust solution with automatic restarts, logging integration, and control over the lifecycle of the daemon.
In summary:
- Write a PHP script with a continuous loop to perform the desired task.
- Make the script executable and run it in the background with
nohup
or manage it usingsystemd
for a more reliable daemon setup.