0

How to pass data from PHP to Python? This is my code. PHP:

$data = 'hello';
$result = shell_exec('/home/pi/Python.py' .$data);

Python:

result = sys.argv[1]
print(result)

But when run python code it show error:

"IndexError: list index out of range".
don't know Why? Is it have other code for pass data from PHP to python?

2
  • 1
    Not sure how it works that far, you seem to be executing the command /home/pi/Python.pyhello Commented Jan 22, 2016 at 10:52
  • add a space between command and arguement Commented Jan 22, 2016 at 10:53

3 Answers 3

3

Provide space between command and argument:

try the following snippet

php : test.php

<?php

$data = 'hello'; 
$output=shell_exec("python test.py "  .$data);

echo $output;


?>

python : test.py

import sys
result = sys.argv[1]
print(result+" by python!")
Sign up to request clarification or add additional context in comments.

Comments

0

You should add space after script name

$data = 'hello';
$result = shell_exec('/home/pi/Python.py ' .$data);

Comments

0

I am creating a machine-learning web application using PHP and here is how I send my data from PHP to Python file. So, I have created a simple PHP and Python file and sent data accordingly.

test.php

<?php
    echo shell_exec("py test.py 1 2 3 ");`
?>

py: is the location of your python.exe. You can either use py or python depending on your operating system. test.py: is the location of your python file. if both PHP and Python are in the same folder, you can write the name of the Python file here. 1 2 3: is the array of data you want to send to the Python file.

test.py

import sys
num_1 = sys.argv[1]
num_2 = sys.argv[2]
num_3 = sys.argv[3]
total = int(num_1)+int(num_2)+int(num_3)
print(total)

Hope it helps 😣

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.