How to Install and Use PHPy to Run Python Code Inside PHP on Ubuntu 22.04
This guide walks you through installing the PHPy extension on Ubuntu 22.04, configuring it, and running a simple PHP script that calls Python code, complete with required packages, configuration steps, and example code.
PHPy is a PHP extension that enables execution of Python code directly from PHP scripts, useful for integrating Python functionality into PHP applications. The article explains how to install PHPy on Ubuntu 22.04 LTS and provides a basic usage example.
System Requirements
Ensure the system runs Ubuntu 22.04.3 LTS. Verify with: cat /etc/os-release If the output contains PRETTY_NAME="Ubuntu 22.04.3 LTS", you can proceed.
Install Required Packages
Install PHP development tools, PECL, and Python development headers:
sudo apt update
sudo apt install php-dev php-pear libpython3-dev python3.10-devInstall PHPy Extension
Locate the Python 3.10 configuration path: which python3.10-config Then install PHPy via PECL: sudo pecl install -f phpy During installation, you’ll be prompted for the Python config path; provide the path found earlier, e.g., /usr/bin/python3.10-config.
After installation, enable the extension by adding extension=phpy.so to the appropriate php.ini (e.g., /etc/php/8.1/cli/php.ini for PHP 8.1) and restart PHP‑FPM or Apache.
Using PHPy
Create example.php with the following content:
<?php
echo "Hello from PHP!
";
// Import Python module
$py = Py::import('sys');
print_r($py->version);
// Define and call a Python lambda
$py_func = Py::evalString('lambda x: x * 2');
echo $py_func(5);
?>This script prints a PHP message, imports Python’s sys module to display its version, defines a Python lambda that doubles a number, and outputs the result.
Run the script with: php example.php You should see the greeting, the Python version, and the computed value (10).
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
Open Source Tech Hub
Sharing cutting-edge internet technologies and practical AI resources.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
