Skip to content
Advertisement

How to pass a variable in PHP from a Python file?

I’m trying to call a Python script in a PHP file and pass a variable value from that script after pressing the submit button. I have it:

index.php

<html>
<body>

<form method="post">
  <input type="submit">
</form>

<?php
if ($_SERVER["REQUEST_METHOD"] == "POST") {
    putenv("HOME=/");
    exec('python test.py'); 
    echo $x;
}
?>

</body>
</html>

test.py

 x = 'ass'

Both files are in the same folder. Why is it not working? I’d like to do this without Flask / Django.

Advertisement

Answer

You can’t declare a variable in Python and use it directly in PHP after execution. Try to output your variable in Python:

x = 'test'    
print(x)

Now you can get the result of your script by the return value of the exec function:

$x = exec('python test.py'); 
echo $x;
User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement