<html>
<body>
<head>
<title>HTML Forms</title>
</head>
<p>Add your details:</p>
<form name="form" method="get">
Number 1:<br> <input type="number" name="first">
<br>
Number 2:<br> <input type="number" name="second">
<br>
Number 3:<br> <input type="number" name="third">
<input type="submit" value="submit" id="submit" />
</form>
</body>
</html>
<?php
$var1 = $_GET['first'];
$var2 = $_GET['second'];
$var3 = $_GET['third'];
$command = escapeshellcmd("python total.py $var1 $var2 $var3");
$output = shell_exec($command);
echo ($output);
?>
import sys
num_1 = sys.argv[1]
num_2 = sys.argv[2]
num_3 = sys.argv[3]
print("total:", num_1+num_2+num_3)
I have shared the code I am using. I want to get the values from user using the HTML code and read it using PHP. Then pass the values from PHP script to python script, do the task and display the output.
For some reason I am unable to do that. Can someone help me?
My Answer:
It looks like there may be an issue with how you are passing the arguments from PHP to Python. In your PHP code, you are using the `escapeshellcmd` function to escape the command, but you are not actually passing the arguments correctly.
Instead of using a single string with all the arguments concatenated, you should pass each argument separately. Here is how you can modify your PHP code to pass multiple arguments to the Python script:
php
$var1 = $_GET['first'];
$var2 = $_GET['second'];
$var3 = $_GET['third'];
$command = "python total.py $var1 $var2 $var3";
$output = shell_exec($command);
echo ($output);
By making this change, each argument will be passed as a separate argument to the Python script, which should allow you to access them correctly in your Python code.
Additionally, in your Python code, you are currently concatenating the arguments as strings. If you want to perform addition on the numbers, you should convert them to integers first. Here is how you can modify your Python code:
python
import sys
num_1 = int(sys.argv[1])
num_2 = int(sys.argv[2])
num_3 = int(sys.argv[3])
print("total:", num_1 + num_2 + num_3)
With these changes, you should be able to pass multiple arguments from PHP to Python and perform the desired task. Let me know if you have any further questions or issues!
Rate this post
4 of 5 based on 5739 votesComments