Execute php code in Python

Execute php code in Python

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

Stefan Bogdanescu

Founder & Senior Architect

Executing PHP Logic from Python Without Translating Legacy Code

Running a legacy PHP script to generate an image directly from Python presents a classic interoperability problem: you need to offload complex, undocumented logic without investing weeks in reverse engineering the algorithm. While the immediate goal is to get data into Python, the architectural solution determines whether that becomes a temporary script or a stable integration point.

The most direct approach involves invoking PHP as an external process within your Python environment. This method bypasses the need for translation entirely by treating PHP as a black-box API. You can achieve this using the subprocess module in standard Python libraries, which allows you to spawn a new process, pass arguments, and capture the output stream.

import subprocess
import os

def get_image_from_php(script_path: str, params: dict) -> bytes:
    # Prepare command-line arguments for the PHP script
    # Use -- to separate options from the script path if needed
    cmd = ['php', script_path] + [f"--{k}={v}" for k, v in params.items()]
    
    try:
        # Execute the process and capture stdout/stderr
        result = subprocess.run(
            cmd,
            capture_output=True,
            text=False,  # Keep binary output as bytes for images
            check=True   # Raise exception if non-zero exit code
        )
        
        if result.returncode != 0:
            raise RuntimeError(f"PHP script failed with exit code {result.returncode}: {result.stderr.decode()}")
            
        return result.stdout
    except FileNotFoundError:
        raise RuntimeError("PHP interpreter not found in PATH. Ensure PHP is installed and accessible.")

# Usage example
image_data = get_image_from_php('/path/to/legacy_script.php', {'width': '1920', 'height': '1080'})

# Save the resulting image to disk
with open('output.png', 'wb') as f:
    f.write(image_data)

This pattern works well for isolated tasks where the PHP script is self-contained. The key technical consideration here is process isolation and environment management. When you spawn a subprocess, it inherits your current working directory and environment variables. If the legacy PHP script relies on specific system paths or global configurations (like php.ini settings or installed extensions), you must ensure those are available in the subprocess context as well.

A critical pitfall to avoid is relying solely on standard output. Many older scripts may write data to STDERR for logging or error reporting. If your Python application expects an image and the PHP script encounters a syntax error, it might print the stack trace to STDERR while leaving STDOUT empty. Your Python wrapper must handle both streams explicitly to provide meaningful debugging information if the subprocess fails.

For more robust integrations where you want to avoid spawning processes repeatedly, consider using message queues or HTTP servers. If the PHP logic can be wrapped in a simple web service (e.g., using FastCGI or a lightweight server like php-fpm), Python can make HTTP requests via requests or aiohttp. This decouples the execution environment from the calling script, allowing you to manage concurrency and error handling at the application level rather than the OS process level.

If the PHP script generates an image file that needs to be processed further in Python, returning binary data directly is preferable to saving intermediate files to disk. However, this requires the PHP script to be configured to output raw bytes without HTML wrappers. Many legacy scripts default to echoing HTML headers. You may need to append <?php ob_start(); ... echo ob_get_clean(); ?> wrappers or modify the script's configuration to ensure it outputs pure binary content.

In cases where the PHP logic is too large to wrap in a single command-line call, splitting the work into distinct services via an API layer often yields better maintainability. This approach aligns with modern microservice architectures, even if the underlying implementation relies on mixed-language runtimes. If your organization has a specific requirement for running PHP scripts within the Python ecosystem, ensure that version compatibility is checked; mixing different major versions of PHP interpreters can lead to subtle runtime errors if the legacy code depends on deprecated functions.

Finally, before committing to this integration pattern, evaluate whether the "big" PHP script contains logic that could be abstracted into a library or a separate microservice. If the only barrier to translation is time, building a bridge via subprocess invocation is an acceptable short-term strategy, but it introduces overhead and dependency on external binaries. For long-term stability, encapsulating the legacy logic behind a clean API—whether through HTTP, sockets, or message queues—is generally superior to direct process invocation.

Our network