How can run python on php? [duplicate]

343
August 28, 2017, at 2:47 PM

This question already has an answer here:

  • Running a Python script from PHP 4 answers

I made a data input web page with a form. And i want to run a python script on the server using the values from the web page and create an output file on the server. Now I can input data and submit the web page. But then python script is not creating the output file on the server.

Below are my scripts.

First, I connect to index.php and input some text on the form and submit it

Below is index.php

<html>
<body>
<form action="1test.php" method="get">
<input type="text" name="name" />
<input type="submit" />
</form>
</body>
</html>

Secondly, 1test.php executes test.py using the form value on index.php.

Below is 1test.php

<?php
$name = $_GET['name'];
$cmd = "python test.py " . $name;
echo $cmd;
exec($cmd);
?>

my script work before python script. I can see $cmd value on web. But php can't execute python. python script has execute permission. Lastly, the python script makes the file on the server. Form values will be array data on python.

Below is test.py

import sys
sip = sys.argv[1]
with open("doc.txt",'w') as f:
        f.write(sip)
f.close()
Answer 1

Try to redirect errors from stderr to stdin with 2>&1 and capture the exit code:

<?php
$name = $_GET['name'];
$cmd = escapeshellcmd("python test.py $name 2>&1");
echo "$cmd" . PHP_EOL;
exec($cmd, $output, $return_var);
echo "$return_var: $output" . PHP_EOL;

If the script returns 0 it means success.

  • exec()
  • escapeshellcmd()
READ ALSO
Trouble finding an installed version of PyAutoGui

Trouble finding an installed version of PyAutoGui

I have been had to reinstall Anaconda and update to Python 36

287
BestMatchAdapter confuse two similar but different questions

BestMatchAdapter confuse two similar but different questions

Using the BestMatchAdapter of Chatterbot, it confuses two questions with the same answerFor example, training the ai

227
Character Movement inside of a 5x5 Grid [on hold]

Character Movement inside of a 5x5 Grid [on hold]

So, i'm making a game, where your a little character, and you move around by typing directionsI have gotten all of that working, but now I want some visualization

177