I`m trying to communicate between my website and a client side script. The Python client sends a POST to a PHP file, which then prints it to show me that the POST is working, so I can move on to the next step of my development. However, for some reason, I can only post to it with an HTML5 form, and not Python 3.5.2 requests module.
This is the PHP:
<?php
$data = ((!empty($_POST['data'])) ? $_POST['data'] : 'N/A');
echo $data;
?>
The Python:
>>> import requests
>>> url = "www.example.com/coords.php"
>>> data = "This is a string"
>>> r = requests.post(url, data)
>>> r.content
b'N/A'
The HTML5 that works:
<html>
<head>
</head>
<body>
<form method="post" action="www.example.com/coords.php">
<input type="text" name="data">
<input type="submit" name="submit">
</form>
</body>
</html>
Your data variable is not correct. Try following:
>>> import requests
>>> url = "www.example.com/coords.php"
>>> data = {'data':'This is a string'}
>>> r = requests.post(url, data)
>>> r.content
b'N/A'
If you check the requests manual you will see that the data
you send should be a dictionary:
>>> import requests
>>> url = "www.example.com/coords.php"
>>> data = "This is a string"
>>> r = requests.post(url, {'data': data})
The key
s that you send (in the dictionary) are the same key
s you should use inside your PHP code.
If you send:
{'key1': 'val1', 'key2': 'val2'}
You should use $_POST['key1']
and $_POST['key2']
in PHP (and their values are val1
& val2
accordingly.