0

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.

1
  • 1
    PHP only sees the output of your python script. It cannot see (and does not understand) any variables declared within the script. Remember they are two separate programs, in two separate languages. Commented Feb 17, 2021 at 13:05

1 Answer 1

2

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;
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.