How can run python on php? [duplicate]

Refresh

December 2018

Views

234 time

1

This question already has an answer here:

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()
KJ9

1 answers

3

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:" . PHP_EOL;
print_r($output);

The $output is an array of lines. If the script returns 0 (value of $return_var), it means success.

LEI