16

PHP code:

<?php
$data=$_POST['data'];
echo $data;
?>

When I do that, the HTML page that Python prints notifies me that PHP did not receive any value in $data I.e:

Error in $name; undefined index

However, when I send the data as GET (http://localhost/mine.php?data=data) and change the PHP method from POST to GET ($data=$_GET['data']), the value is gotten and processed.

My main issue here is that it seems the value in data does not go through to PHP as I would have wanted to use POST. What could be wrong?

Peter O.
  • 32,158
  • 14
  • 82
  • 96
Crazywizard
  • 161
  • 1
  • 1
  • 3

4 Answers4

34

Look at this python:

import urllib2, urllib
mydata=[('one','1'),('two','2')]    #The first is the var name the second is the value
mydata=urllib.urlencode(mydata)
path='http://localhost/new.php'    #the url you want to POST to
req=urllib2.Request(path, mydata)
req.add_header("Content-type", "application/x-www-form-urlencoded")
page=urllib2.urlopen(req).read()
print page

Almost everything was right there Look at line 2

heres the PHP:

<?php
echo $_POST['one'];
echo $_POST['two'];
?>

this should give you

1
2

Good luck and I hope this helps others

TheBestJohn
  • 597
  • 1
  • 6
  • 14
6

There are plenty articles out there which suggest using requests rather then Urllib and urllib2. (Read References for more Information, the solution first)

Your Python-File (test.php):

import requests
userdata = {"firstname": "John", "lastname": "Doe", "password": "jdoe123"}
resp = requests.post('http://yourserver.de/test.php', params=userdata)

Your PHP-File:

$firstname = htmlspecialchars($_GET["firstname"]);
$lastname = htmlspecialchars($_GET["lastname"]);
$password = htmlspecialchars($_GET["password"]);
echo "firstname: $firstname lastname: $lastname password: $password";

firstname: John lastname: Doe password: jdoe123

References:

1) Good Article, why you should use requests

2) What are the differences between the urllib, urllib2, and requests module?

Community
  • 1
  • 1
user1767754
  • 23,311
  • 18
  • 141
  • 164
5
import urllib
import urllib2

params = urllib.urlencode(parameters) # parameters is dicitonar
req = urllib2.Request(PP_URL, params) # PP_URL is the destionation URL
req.add_header("Content-type", "application/x-www-form-urlencoded")
response = urllib2.urlopen(req)
Ilian Iliev
  • 3,217
  • 4
  • 26
  • 51
0

looking arround I only found this post, it was a start point but I had to search a lot to update it, I like to post an update for the TheBestJohn's answer because he send the original one.

note: the php is the same

import urllib.request
import urllib.parse

mydata=[('one','128'),('two','247')]
mydata=urllib.parse.urlencode(mydata)
utf8 = bytes(mydata, 'utf-8')
path='http://localhost/new.php'
page=urllib.request.urlopen(path, utf8, 300).read()
print(page)
Jorge Raigoza
  • 11
  • 1
  • 1