Having trouble with performing a POST instead of a GET in Python Urllib. Im running 3.5. Im trying to POST to form field.
I read that urllib.request.Request will default to POST if the data parameter is present. I read this at https://docs.python.org/3/howto/urllib2.html
I duplicate these settings and when I fire up wireshark all I see is GETs and Never a Post even though it looks like the code is executing.
Here is my code:
values = {"field1" : z[2:-1], "Submit":"Save"}
print(values)
data = urllib.parse.urlencode(values)
data = data.encode('utf-8')
print(data)
req = urllib.request.Request("http://www.randomsite.com/myprocessingscript.php", data)
with urllib.request.urlopen(req) as response:
the_page = response.read()
print(the_page)
When I fireup wireshark this is what results from the req line:
GET /myprocessingscript.php HTTP/1.1 Accept-Encoding: identity Host: ec2-52-91-45-113.compute-1.amazonaws.com Connection: close User-Agent: Python-urllib/3.5
HTTP/1.1 200 OK Date: Wed, 28 Oct 2015 02:47:22 GMT Server: Apache/2.4.17 (Unix) OpenSSL/1.0.1p PHP/5.5.30 mod_perl/2.0.8-dev Perl/v5.16.3 X-Powered-By: PHP/5.5.30 Content-Length: 23 Connection: close Content-Type: text/html
no post data to process
ADDITIONALLY When I run the script, this is what i get from the print statements:
{'Submit': 'Save', 'field1': 'hostlab\chris'} b'Submit=Save&field1=hostlab%5Cchris%5Cr%5Cn' b'no post data to process' Traceback (most recent call last): File "C:\Users\chris\Desktop\test.py", line 20, in time.sleep(random.randint(5,10))
There are two web files they are accessing. Index.html and myprocessingscript.php:
Index.html:
<h1>randomsite.com.</h1>
####<p>whoami</p>
<form action="myprocessingscript.php" method="POST">
<input name="field1" type="text" />
<input type="submit" name="submit" value="Save">
</form>
</body>
</html>
myprocessingscript.php:
<?php if(isset($_POST['field1'])) {
$data = $_POST['field1'] . "\n";
$ret = file_put_contents('/tmp/mydata.txt', $data);
if($ret === false) {
die('There was an error writing this file');
}
else {
echo "$ret bytes written to file";
}
}
else {
die('no post data to process');
}