Sending Data Using Post in Python to PHP

Sending POST with Python to PHP

For anyone experiencing the same problem as me, I solved it by adding a header to my post request like so:

import requests

url = 'http://******.com/***/test.php'
query = {'site': 'test'}

res = request.post(url, query, headers={"User-Agent": "Firefox/12.0"})
print(res)

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

Check out the urllib and urllib2 modules.

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

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

Simply create a Request object with the needed data. Then read the response from your PHP service.

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

Python Post - PHP Request

When you make a HTTP request to a server, that server will return the rendered webpage to that user. This means requests will get back the correct response.

However when you open a web page in a browser, you are making a new request to that server which will render the page again. Since you aren't passing the $_REQUEST['iv'] etc. values this time, the table will appear blank.

You have a few options depending on what you want to do:

Store the information in a database

You can store that information in a database. Some databases for example are SQLite3 or MySQL. I've omitted the exact database insertion/reading implementation since it differs between which database you pick.

A simple method might be:

<?php

$iv=$_REQUEST['iv'];
// insert other variables etc.

// Check if this is a POST request
if ($_SERVER['REQUEST_METHOD'] === "POST") {
// INSERT DATA INTO YOUR DATABASE AS APPROPRIATE
// You can also echo back the table if you want

// Else it might be a GET request
} elseif ($_SERVER['REQUEST_METHOD'] === "GET") {
// READ DATA FROM DATABASE
// echo table with the data from the database
}

?>

Use URL parameters

Alternatively you can use URL parameters to encode your data like so:

# In your Python code
# Notice that requests.post changed to requests.get and data changed to params
r = requests.get('http://localhost/index.php', params={"iv":a,"ven":b,"hem":c,"card":d,"ecg":e})

# You can now access this specific URL to see the populated table
# The URL will look something like http://localhost/index.php?iv=a&ven=b/
print(r.url)

Note that this requires you to visit that specific URL and doesn't work if you visit the base URL (i.e. https://localhost/index.php) without the parameters.



Related Topics



Leave a reply



Submit