PHP for System Programming: From Scripts to Daemons

Online Python Trainer for Beginners

Learn Python easily without overwhelming theory. Solve practical tasks with automatic checking, get hints in Russian, and write code directly in your browser — no installation required.

Start Course

When PHP Goes Beyond the Web

\n

Imagine a situation: you need to write a daemon that monitors system logs, parses them, and sends notifications to Telegram. Or perhaps you need to create your own task scheduler that doesn't depend on cron. What if you need to write your own simple web server or proxy? Most developers would immediately reach for Python, Go, or C. But what if I told you that PHP can also handle system programming? And it does it quite well.

\n

PHP is not just a language for "WordPress sites." Its CLI version (Command Line Interface) is a full-fledged tool for system administration, working with processes, network sockets, and even daemonization. In this article, we will explore how to use PHP for system programming and show real code examples that work on Linux.

\n\n

Preparation: What You Need to Know

\n

First, make sure you have PHP installed with CLI support and the pcntl (process control), posix (system calls), and sockets (socket programming) extensions. On most Linux distributions, this is done with a single command:

\n
sudo apt install php-cli php-pcntl php-posix php-sockets
\n

You can check the availability of extensions using php -m | grep -E 'pcntl|posix|sockets'. If everything is in place, let's go.

\n\n

Working with Processes: fork and exec

\n

PHP allows you to create child processes using the pcntl_fork() function. This is a powerful mechanism for parallel task execution. Let's look at an example that launches three child processes, each performing its own work.

\n
<?php\n$workers = 3;\n$pids = [];\n\nfor ($i = 0; $i < $workers; $i++) {\n    $pid = pcntl_fork();\n    if ($pid == -1) {\n        die("Failed to create process");\n    } elseif ($pid) {\n        // Parent process: save the child PID\n        $pids[] = $pid;\n        echo "Created child process PID: $pid\\n";\n    } else {\n        // Child process\n        echo "Child process " . getmypid() . " started working\\n";\n        sleep(rand(2, 5)); // Simulate work\n        echo "Child process " . getmypid() . " finished\\n";\n        exit(0);\n    }\n}\n\n// Parent waits for all child processes to finish\nforeach ($pids as $pid) {\n    pcntl_waitpid($pid, $status);\n    echo "Process $pid finished with status $status\\n";\n}\n?>
\n

This code demonstrates basic multitasking in PHP. You can run parallel tasks — parsing logs, processing files, making network requests. In system programming, this approach is indispensable when you need to process large amounts of data without blocking the main thread.

\n\n

Executing External Commands

\n

The exec() function and its variants (shell_exec(), system()) allow you to run any system commands. But for real system programming, it's better to use proc_open() — it gives you full control over the input/output and the process PID.

\n
<?php\n$descriptorspec = [\n    0 => ["pipe", "r"],  // stdin\n    1 => ["pipe", "w"],  // stdout\n    2 => ["pipe", "w"]   // stderr\n];\n\n$process = proc_open('ping -c 4 8.8.8.8', $descriptorspec, $pipes);\n\nif (is_resource($process)) {\n    // Read output\n    $output = stream_get_contents($pipes[1]);\n    fclose($pipes[1]);\n    fclose($pipes[2]);\n    proc_close($process);\n    \n    echo "Ping result:\\n$output";\n}\n?>
\n

This approach allows you to integrate PHP with any system utilities — from ps to ffmpeg.

\n\n

Signal Handling: Making a Daemon Polite

\n

Any serious daemon must correctly handle operating system signals. PHP, through the pcntl extension, allows you to intercept signals (SIGTERM, SIGHUP, SIGUSR1, and others). This is a key skill

Blogs

Book Recommendations