How to Run a Python Script from PHP

It’s very simple to run a Python script from a PHP file with the shell_exec function, which allows you to run Python script files from PHP.

PHP (hypertext preprocessor) is a widely used free and open-source scripting language for web developers, and Python is known for its simplicity and versatility, which make it a popular choice for building complex web applications.

It would be much more convenient if we could use Python and PHP, both scripting languages, in one program.

And to run or facilitate Python scripts in PHP, we can use the shell_exec function, which returns all of the output streams as a string. The shell executes it, and the result can be returned as a string.

So, let’s learn how to execute a Python script in PHP.

How to Execute a Python Script in PHP

To perform all the below steps properly, you need to install Python and a web server.

To install a web server, if you are on a Windows or Linux operating system, go for XAMPP, or else you can also manually install Apache and PHP on Linux,which is a cross-platform web server.

You can also get instant Python assignment help at AssignmentCore from top experts who know how to cope with your problems.

Step 01Create a Python Script

First, we will create a Python script file and store it in the respective directory so that it can be accessed by the PHP file when you execute the script.

For XAMPP users, make sure to store files in the htdocs directory of your respective web directory.

Now let’s create a short & simple program that returns “TREND OCEANS” as output.

Open a command-line editor and paste the following line code: where we have used the shebhang line to declare the path of the Python binary file, and then we put “TREND OCEANS” under the print function to print.

#!/usr/bin/env python3
print("TREND OCEANS")

After adding the line Save and close the file with a .py extension, like here, I have saved with test.py.

Step 2Create a PHP file

To run Python scripts in PHP, we use two functions of PHP.

escapeshellcmd() escapes all characters in a string that can trick a shell command into executing arbitrary commands.

shell_exec() that returns all of the output streams as a string.

Now we create a PHP file and save it in the same location where we have saved our Python script.

<?php
    $command = escapeshellcmd('python3 test.py');
    $output = shell_exec($command);
    echo $output;
?>

Save the above script with the .php extension.

Step 3Run Script

Start your web server and visit your web server domain. In my case, I’ve demonstrated on my localhost, so I visit http://localhost with the file name sample.php on my browser.

Run Python script from PHP result
Output on Browser

If you perform all steps properly above output will be displayed on your browser.

Also Read: How to Run JavaScript in Python (with an Example)

Bonus (One More Short Demo)

In this method, you do not need to install a web server. You just need to have a PHP installation, and if you don’t have it, check out this guide.

Here, I do have PHP and Python installed, so let me write one more short script to print system information like hostname, platform, architecture, and date.

Open your system command line editor, paste the following lines of code, and save the file with system.py name.

#!/usr/bin/env python3

import platform
from datetime import date

system_hostname = platform.uname().node
platform_name = platform.system()
machine_arch = platform.machine()
current_date = date.today()

print("Hostname Info:", system_hostname)
print("Platform:", platform_name)
print("Machine Architecture:", machine_arch)
print("Current Date:", current_date)

After that, create a new file with the name sample.php & copy and paste the following lines of script, then save the file.

<?php 
$system_info = shell_exec("./system.py");

echo $system_info;

Next, you have to test the functionality of the script by running the next line of commands. But before that, you need to make the script executable. Otherwise, you may get sh: 1: ./system.py: Permission denied.

To avoid this, execute the following line of code, then run the PHP file to execute the inner script.

$ chmod u+x system.py
$ php system_info.php         

The result of the above-mentioned procedures

Run Python script file in PHP
Run a Python script file in PHP

Wrap up

That’s all for this guide, where I showed you how to execute or run Python scripts in PHP using the shell_exec function with two different examples.

If you have a query, feel free to ask it in the comment section.

See you in the next article… spread ☮️ and ❤️.

0 0 votes
Article Rating
Subscribe
Notify of
guest
5 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
Samuel Vizcarra Aguilar
Samuel Vizcarra Aguilar
3 years ago

thank you Jake Redfield

chris ockenden
chris ockenden
2 years ago

Hi thankyou I have a lot of python code and it is not displaying using this, is it because I have a lot of database calls and the browser is not set to wait for it?

Unbreaker
Unbreaker
1 year ago

thanks brother