Sending data using POST in Python to PHP

ぐ巨炮叔叔 提交于 2019-11-27 07:29:51

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

user1767754

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?

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)
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!