Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Calling Python in PHP

Tags:

python

php

I have a Python script I recently wrote that I call using the command line with some options. I now want a very thin web interface to call this script locally on my Mac.

I don't want to go through the minor trouble of installing mod_python or mod_wsgi on my Mac, so I was just going to do a system() or popen() from PHP to call the Python script.

Any better ideas? Thanks in advance!

like image 686
Benny Wong Avatar asked Oct 03 '08 13:10

Benny Wong


People also ask

Can PHP interact with Python?

Yes it will work, and how risky it is depends on how good your implementation is. This is perfectly acceptable if done correctly. I have successfully integrated PHP and C, when PHP was simply too slow to do certain niche tasks in real time (IIRC, PHP is 7 times slower than its C counterpart).

How do I communicate with Python and PHP?

You want inter-process communication. Sockets are the first thing that comes to mind; you'd need to set up a socket to listen for a connection (on the same machine) in PHP and set up a socket to connect to the listening socket in Python and send it its status.

Can I use xampp for Python?

Add Python to XAMPP's Apache conf is in XAMPP. For Windows, you can open the XAMPP Control Panel and click on Config > Apache (httpd. conf).


2 Answers

Depending on what you are doing, system() or popen() may be perfect. Use system() if the Python script has no output, or if you want the Python script's output to go directly to the browser. Use popen() if you want to write data to the Python script's standard input, or read data from the Python script's standard output in php. popen() will only let you read or write, but not both. If you want both, check out proc_open(), but with two way communication between programs you need to be careful to avoid deadlocks, where each program is waiting for the other to do something.

If you want to pass user supplied data to the Python script, then the big thing to be careful about is command injection. If you aren't careful, your user could send you data like "; evilcommand ;" and make your program execute arbitrary commands against your will.

escapeshellarg() and escapeshellcmd() can help with this, but personally I like to remove everything that isn't a known good character, using something like

preg_replace('/[^a-zA-Z0-9]/', '', $str) 
like image 77
Andru Luvisi Avatar answered Oct 17 '22 10:10

Andru Luvisi


The backquote operator will also allow you to run python scripts using similar syntax to above

In a python file called python.py:

hello = "hello" world = "world" print hello + " " + world 

In a php file called python.php:

$python = `python python.py`; echo $python; 
like image 45
user Avatar answered Oct 17 '22 09:10

user