Sending User input from python to php

Viewed 114

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.

2 Answers

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);

?>

requests.post needs dict object, not str.

So posting data with requests,

data = {'userdata': message}
resp = requests.post(url, data=data)

Edit

data = {'userdata': message}
resp = requests.get(url, params=data)
Related