Skip to content
Advertisement

Sending User input from python to php

This is my python file:

host = socket.gethostname()

mac = hex(uuid.getnode())

sign = host + mac
message = input('plz enter message')
userdata = { message, sign}
url = "http://localhost:8081/project/server.php"
resp = requests.post(url,  data=str(userdata))

print(resp.text)

This is my PHP Script:

<?php

if (isset($_GET['userdata'])){
    $userdata = $_GET['userdata'];
    echo $userdata;
 }
else{
     echo "Data not received";
 }
echo $userdata ;
?>

Problem my python file is not sending userdata to php script. Any help would be appreciated Thank you.

Advertisement

Answer

The problem is you are sending post data but in PHP script, you are capturing GET data. We can re-write both files like this to send POST data and capture POST data

Python file

sign = host + mac
message = input('plz enter message')
url = 'http://localhost:8081/project/server.php'
postdata = {'sign': sign , 'msg' : message }

x = requests.post(url, data = postdata)

print(x.text)

PHP file

 <?php

if (isset($_POST['sign'])) {
    $myfile = fopen("data", "a");
    $sign = $_POST['sign'];
    $msg = $_POST['msg'];

    echo $sign . " " . $msg ;
    fwrite($myfile , $sign.','.$msg."n");
    fclose($myfile);
}
else {
    echo "Data not received <br/>";
}

$myfile = fopen("data", "r");

while(!feof($myfile)) {
    echo fgets($myfile). "<br/>";
}
fclose($myfile);

?>
User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement