How to send an HTTP POST value to a page (PHP) using Python?

I have a PHP page that has 1 text box and when I click the submit button. My SQL will store this product name in my database. My question is: is it possible to send / send the product name using a Python script that requests 1 value and then use my PHP page to send it to my database? Thank you

+1
source share
6 answers

Check urllib and urllib2 modules.

http://docs.python.org/library/urllib2.html

http://docs.python.org/library/urllib.html

Just create a Request object with the required data. Then read the answer from your PHP service.

http://docs.python.org/library/urllib2.html#urllib2.Request

+5

-, python, twill. Twill - , cookie HTML- .

, -, :

from twill import commands
commands.go('http://example.com/create_product')
commands.formvalue('formname', 'product', 'new value')
commands.submit()

, .

+3

http://www.voidspace.org.uk/python/articles/urllib2.shtml, urllib2, , , .

import urllib
import urllib2

url = 'http://www.someserver.com/cgi-bin/register.cgi'
user_agent = 'Mozilla/4.0 (compatible; MSIE 5.5; Windows NT)'
values = {'name' : 'Michael Foord',
          'location' : 'Northampton',
          'language' : 'Python' }
headers = { 'User-Agent' : user_agent }

data = urllib.urlencode(values)
req = urllib2.Request(url, data, headers)
response = urllib2.urlopen(req)
the_page = response.read()

urllib, HTTP POST. GET, urlencode.

read(), .

+3

. urllib2 - Python / HTTP-.

+2

. , HTTP- Python, .

, HTTP, . (, urllib socket)

, python, POST :

import requests
userdata = {"firstname": "Smith", "lastname": "Ayasaki", "password": "123456"}
resp = requests.post('http://example.com/test.php', data = userdata)

text.php, :

$firstname = htmlspecialchars($_POST["firstname"]);
$lastname = htmlspecialchars($_POST["lastname"]);
$password = htmlspecialchars($_POST["password"]);
echo "FIRSTNAME: $firstname  LASTNAME: $lastname  PW: $password";

, (resp.content python) :

FIRSTNAME: Smith LASTNAME: Ayasaki PW: 123456

+1
source

Just adding to the @antileet procedure , it works the same way if you are trying to execute an HTTP POST request with a payload similar to a web service, except for you just omit the urlencode step; i.e.

import urllib, urllib2

payload = """
<?xml version='1.0'?>
<web_service_request>
    <short_order>Spam</short_order>
    <short_order>Eggs</short_order>
</web_service_request>
""".strip()
query_string_values = {'test': 1}
uri = 'http://example.com'

# You can still encode values in the query string, even though
# it a POST request. Nice to have this when your payload is
# a chunk of text.
if query_string_values:
    uri = ''.join([uri, '/?', urllib.urlencode(query_string_values)])
req = urllib2.Request(uri, data=payload)
assert req.get_method() == 'POST'
response = urllib2.urlopen(req)
print 'Response:', response.read()
0
source

Source: https://habr.com/ru/post/1730373/


All Articles