PHP Interacting with Python
Last Updated on Mar 22, 2023
Both PHP and Python are very powerful languages. Sometimes you might want to run a python program from your PHP code. It might be a machine learning algorithm, a crawler or anything else.
It’s very easy to do that.
Do you remember when we talked about running system commands?
We can use the same command and run a python program
Here my python file looks like this:
print("Hello My Friend!")
I can now use the exec function run the command and store the output and then echo that in php like this:
exec('python ./sayHello.py', $output); // output is: Array (  => Hello amir ! ) echo $output; // Hello My Friend!
It’s always a good idea to escape all the shell commands. To do that you can use escapeshellcmd Function.
This escapes any characters in a string that might be used to trick a shell command into executing arbitrary commands.
So let’s make our code more secure:
$command = escapeshellcmd('python ./sayHello.py); exec($command, $output); echo $output; // Hello My Friend!
Sometimes your python code might accept some command line arguments. We can also pass those arguments from our PHP code.
My updated python code looks like this:
import sys if len(sys.argv) > 1: name = sys.argv print("Hello",name.capitalize(),'!') else: print("Hello My Friend!")
Now if I pass the name it says hello and the name but if I don’t pass any name it will say Hello My Friend
Now let’s pass the name with PHP
$command = escapeshellcmd('python ./sayHello.py amir'); exec($command, $output); echo $output; // Hello Amir !
And if I don’t pass the name:
$command = escapeshellcmd('python ./sayHello.py'); exec($command, $output); echo $output; // Hello My Friend!
Now you know about running a python code from PHP.
I recommend you to open a PHP files and try to run a simple python code from PHP. then try to pass arguments and parse the response.
If you have any suggestions, questions, or opinions, please contact me. I’m looking forward to hearing from you!
- run a python code from php
- how to make system commands more secure
- exec and escapeshellcmd function