How to Run a Python Script in PHP

PHP (which is a recursive acronym for PHP Hypertext Preprocessor) is one of the most widely used web development technologies in the world. PHP code used for developing websites and web applications can be embedded directly along with the rest of the HTML markup. This, along with a rich amount of libraries to perform system tasks, or to integrate with other application, makes PHP the go-to language for the Internet.

While there are plenty of libraries (or modules) in PHP, there can be cases when a module for a certain task is either missing or is not properly implemented; while the same module is available in Python.

Apart from this, for certain scripting tasks the user might find Python more suitable, while he finds PHP suitable for the rest of his codebase.

In this article, we will take a look at how a Python script can be run from a PHP interpreter in a Linux terminal.

Calling a Python Script in PHP

Let us consider the following PHP code (test.php).

<?php 
$string = 'Example String\n'; 
?>

Note: The '\n' at the end of the string is a newline character, which will move the cursor to the new line for the next commands on the terminal.

Let’s now call a simple Python script ‘test.py’, which simply prints ‘Hello World’.

$ cat test.py

print(“Hello World”)

To call this script from PHP, use the ‘exec’ function.

<?php 
$string = 'Example String\n'; 
$pyout = exec(‘python test.py’);
echo $pyout;
echo “\n”;
?>

We can call the script with the command line program ‘php’, which is nothing but the PHP interpreter.

$ cat test.py
$ cat test.php
$ php test.php
Run Python Script Using PHP
Run Python Script Using PHP

As we can see, the output of Python script test.py was displayed.

Next, let’s consider the following Python script file, ‘test2.py’, which takes one argument, a String, and prints it.

$ cat test2.py

import sys
print(sys.argv[1])

Now let’s call this script from PHP, passing the argument.

$ cat test.php
$ php test.php
Execute Python Script Using PHP
Execute Python Script Using PHP

As we can see, the Python Script got executed and printed the parameter value ‘Example’.

Conclusion

In this article, we saw how to call a Python script from within our PHP code. This can be used on more complex Python scripts, the output of which will be stored in the PHP variable as shown in our examples above.

This can especially be helpful when some complex Python libraries, eg. the machine learning and data science libraries, are to be used. If you have any questions or feedback, make sure you leave a comment below!

Got something to say? Join the discussion.