Calling Python in PHP

Calling Python in PHP

  1. Blog
  2. 15 November 2026
  3. 3 min read

Stefan Bogdanescu

Founder & Senior Architect

Calling Python in PHP: Beyond system() and popen()

You have a working Python CLI script on your Mac that accepts arguments, and you need a thin web layer to execute it. While invoking the script via shell_exec(), system(), or popen() from PHP is technically feasible, relying on raw system calls introduces significant operational overhead and security friction. The goal here isn't just to get output; it's to manage processes robustly without introducing unnecessary complexity like configuring Apache modules or managing complex reverse proxies.

Using shell_exec() is the simplest path for capturing full output as a string, but it offers zero control over process termination. If your Python script hangs or enters an infinite loop, the PHP request will wait indefinitely, eventually exhausting the web server's worker pool or causing the entire site to become unresponsive. You need a mechanism to ensure the Python process dies when the PHP response times out, regardless of whether the script is designed to run for hours or seconds.

A more controlled approach involves leveraging the operating system's job control features directly. On macOS (and Linux), you can spawn the Python script in a background process and redirect its output to a file descriptor that PHP can read from. However, this often leads to messy signal handling issues where SIGPIPE errors occur if the parent PHP process closes the stream before the child writes data.

A cleaner architectural pattern is to use a message queue or a simple IPC mechanism between the web layer and the script execution layer. If you are already using a framework like Laravel, you could consider offloading the execution entirely to a background job queue (like Redis or RabbitMQ), pushing a payload that triggers the Python script, and polling for completion. However, if you want a synchronous response where the PHP page waits for the script to finish—say, generating a report and returning it immediately—you should treat the Python invocation as a distinct subprocess with strict resource constraints.

Here is a practical implementation using proc_open instead of shell_exec. This function gives you direct control over standard input/output/error streams and allows you to set specific environment variables or working directories without spawning unnecessary shells:

<?php

$cmd = '/usr/bin/python3 /path/to/script.py --option value';
$descriptorSpec = [
    0 => ['pipe', 'r'],   // stdin
    1 => ['pipe', 'w'],   // stdout
    2 => ['pipe', 'w']    // stderr
];

$process = proc_open($cmd, $descriptorSpec, $pipes);

if (is_resource($process)) {
    // Set a timeout to prevent hanging requests
    stream_set_timeout(fopen($pipes[1], 'rb'), 30); 
    
    $output = '';
    while (!feof($pipes[1])) {
        $chunk = fread($pipes[1], 4096);
        if ($chunk !== false) {
            $output .= $chunk;
        } else {
            break; 
        }
    }

    // Ensure the process is killed regardless of stream status
    proc_close($process);

    echo $output;
} else {
    http_response_code(500);
    echo 'Failed to start script.';
}
?>

While effective, this approach still couples the PHP request lifecycle directly to the Python process. If your Mac has limited memory or CPU, spawning a new process for every request can degrade performance. Furthermore, handling errors from the child process requires careful parsing of stderr to distinguish between expected warnings and fatal failures.

If you find yourself needing more sophisticated orchestration—such as logging outputs to persistent files, managing retries, or ensuring the script runs with specific permissions—you might consider a dedicated entrypoint service. This service listens for requests and executes the Python code in an isolated environment. For many local development setups on macOS, sticking to proc_open with explicit timeouts and stream wrapping is often sufficient. It avoids the overhead of installing mod_wsgi or setting up a full containerized stack while providing better control than simple system calls.

Ultimately, the decision rests on whether you need true concurrency or synchronous execution. If synchronous execution is required, always implement timeouts to protect your web server from resource exhaustion. If you are building this for production rather than local Mac development, consider decoupling the layers entirely so that the Python script can run in a container or a dedicated daemon, allowing PHP to simply query status via an API.

Our network