How to Run a Python Script from PHP

  • Post last modified:April 27, 2021
  • Reading time:2 mins read

PHP (PHP: Hypertext Preprocessor) is a widely used free and open-source scripting language for a web developer.

To run Python Script in PHP, we use “shell_exec” which returns all of the output streams as a string. The shell executes it, and the result can be returned as a string.

It returns an error or no output at all if an empty value is passed.

Today we guide you on 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 windows or Linux user, go for XAMPP, which is a cross-platform web server.

Step 1: Create a Python Script

First, we create a python script and if you are using the XAMPP server for PHP, then save it in the htdocs directory of your respective web directory where your web server looks for the file to serve on your domain.

Now create a simple program that returns TrendOceans as output. Write or copy-paste the below code into a file with .py extension and save it in your respective web server directory.

#!/usr/bin/env python
print("TrendOceans")

Save and close the file. In my case, I have save with name test.py.

Step 2: Create a PHP file

To run Python Script in PHP we use two function 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('python test.py');
    $output = shell_exec($command);
    echo $output;
?>

Save the above script with the .php extension. Start your webserver and visit your web server domain. In my case, I’ve demonstrated in my localhost, so I visit http://localhost on my browser.

Output on Browser

If you perform all steps properly above output will be displayed on your browser. If you have a query, feel free to ask in the comment section.

Like what you read? Please share it with others.
  • 1
    Share
guest
0 Comments
Inline Feedbacks
View all comments