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!
Advertisement
Answer
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)