POSTing binary data over http with Python -> PHP - php

I'm want to post a binary data string from a Python script to a webserver where a PHP script should pick it up and store it. I receive the whatever I echo in my POST part of the php script on the Python side so I assume, the actual POST works. However, I'm posting 23 Bytes and strlen($_POST['data']) stays 0.
My PHP script to pickj up the data looks like this:
if (isset($_REQUEST["f"]) && $_REQUEST["f"]=="post_status") {
$fname = "status/".time().".bin";
if (file_exists($fname)) {
$fname = $fname."_".rand();
if (file_exists($fname)) {
$fname = $fname."_".rand();
}
}
echo strlen($_POST['data'])." SUCCESS!";
}
and the Python POST script looks like this:
data = statusstr
host = HOST
func = "post_status"
url = "http://{0}{1}?f={2}".format(host,URI,func)
print url
r = urllib2.Request(url, data,{'Content-Type': 'application/octet-stream'})
r.get_method = lambda: 'PUT'
response = urllib2.urlopen(r)
print "RESPONSE " + response.read()
Why does my data not seem to get through, I'm wondering?
Thank you,

PHP will only populate posted values into the $_POST/REQUEST arrays for data that is sent as one of the form data content types. In your case, you need to read in the binary data directly from standard in like this:
$postdata = file_get_contents("php://input");

Related

Unable to send data using POST in Python

I am trying to send data using POST from StachExchange API. I am not sure what seems to be the problem. I have checked the script, it's working fine when I try to POST data some other way. The problem seems to be with the python script. The scripts gets the data from the API but doesn't seems to be posting to "generate.php" Nonetheless here's the code:
#!/usr/bin/env python
import requests, json
userinput = input('Enter a keyword: ')
userinputq = input('Enter page: ')
getparams = {'page':userinputq, 'pagesize':'100', 'order':'desc', 'sort':'votes', 'intitle':userinput, 'site':'stackoverflow', 'filter': '!5-HwXhXgkSnzI0yfp0WqsC_-6BehEi(fRTZ7eg'}
r = requests.get('https://api.stackexchange.com/2.2/search', params=getparams)
result = json.loads(r.text)
if result['has_more'] == False:
print("Error given.")
else:
for looping in result['items']:
if looping['is_answered'] == True:
try:
newparams = {'order':'desc', 'sort':'votes', 'site':'stackoverflow', 'filter': '!4(Yrwr)RRK6oy2JSD'}
newr = requests.get('https://api.stackexchange.com/2.2/answers/'+str(looping['accepted_answer_id']), params=newparams)
newresult = json.loads(newr.text)
titletopost = 'Title:', looping['title']
bodytopost = '<h1>Question:</h1><br>'+(looping['body'])+'<br>'+'Link to Question: '+(looping['link'])+'<br><br><br>'+'<h1>Answer:</h1><br>'+(newresult['items'][0]['body'])
enterremove = bodytopost.replace('\n', '').replace('\r', '')
print(enterremove)
userdata = {"secret":"Secret", "topic_title":titletopost, "body":enterremove}
requests.post("http://www.example.com/generate.php", data=userdata)
except KeyError: print("No answer ID found.")
print("")
print("")
Can anyone please explain the problem?
Nevermind! There's nothing wrong with the python script. Actually I forgot to change "$_GET" to "$_POST" in 'generate.php' while I was testing it.

Pass JSON Data from PHP to Python Script

I'd like to be able to pass a PHP array to a Python script, which will utilize the data to perform some tasks. I wanted to try to execute my the Python script from PHP using shell_exec() and pass the JSON data to it (which I'm completely new to).
$foods = array("pizza", "french fries");
$result = shell_exec('python ./input.py ' . escapeshellarg(json_encode($foods)));
echo $result;
The "escapeshellarg(json_encode($foods)))" function seems to hand off my array as the following to the Python script (I get this value if I 'echo' the function:
'["pizza","french fries"]'
Then inside the Python script:
import sys, json
data = json.loads(sys.argv[1])
foods = json.dumps(data)
print(foods)
This prints out the following to the browser:
["pizza", "french fries"]
This is a plain old string, not a list. My question is, how can I best treat this data like a list, or some kind of data structure which I can iterate through with the "," as a delimiter? I don't really want to output the text to the browser, I just want to be able to break down the list into pieces and insert them into a text file on the filesystem.
Had the same problem
Let me show you what I did
PHP :
base64_encode(json_encode($bodyData))
then
json_decode(shell_exec('python ' . base64_encode(json_encode($bodyData)) );
and in Python I have
import base64
and
content = json.loads(base64.b64decode(sys.argv[1]))
as Em L already mentioned :)
It works for me
Cheers!
You can base64 foods to string, then passed to the data to Python and decode it.For example:
import sys, base64
if len(sys.argv) > 1:
data = base64.b64decode(sys.argv[1])
foods = data.split(',')
print(foods)
If you have the json string: data = '["pizza","french fries"]' and json.loads(data) isn't working (which it should), then you can use: MyPythonList = eval(data). eval takes a string and converts it to a python object
Was having problems passing json from PHP to Python, my problem was with escaping the json string, which you are doing. But looks like you were decoding then re-encoding with "food"
From what I understand
Python json.dumps(data) == PHP json_encode(data)
Python json.loads(data) == PHP json_decode(data)
json.loads(data) -> String Data
json.load(data) -> File Data
json.dumps(data) -> String Data
json.dump(data) -> File Data
PHP:
$foods = array("pizza", "french fries");
$result = shell_exec('python ./input.py ' . escapeshellarg(json_encode($foods)));
echo $result;
Python:
data = json.loads(sys.argv[1])
for v in data:
print(v)
ALSO
if you are passing key:value
PHP:
$foods = array("food1":"pizza", "food2":""french fries");
$result = shell_exec('python ./input.py ' . escapeshellarg(json_encode($foods)));
echo $result;
Python:
data = json.loads(sys.argv[1])
for(k,v) in content2.items():
print("k+" => "+v)
Python:
data = json.loads(sys.argv[1])
print(data['food1'])

sending the json data from python to php

I am sending the json data from a python program using the below code
import json
import requests
data = {"temp_value":132}
data_json = json.dumps(data)
payload = {'json_playload': data_json}
r = requests.get('http://localhost/json1/js2.php',data=payload)
and receiving it in a php server side using the below code.
<?php
if($_GET['temp_value']) {
$temp_value = $_GET['temp_value'];
echo $temp_value;
# $data = array($id, $description);
$arr=json_decode($temp_value,true);
} else {
echo "not found";}
// Connect to MySQL
include("dbconnect.php");
// Prepare the SQL statement
$SQL = "INSERT INTO test1.temperature1 (temp_value) VALUES ('$arr')";
// Execute SQL statement
mysqli_query($dbh,$SQL);
Echo "<a href=http://localhost/json1/review_data.php><center><u><b><h1>Manage values<h1><b><u></center></a>"
?>
along with the json data I have implemented like Id,time and date also gets updated in the database when i send the data.But what is happening here is like whenever i send the data from the python program it won't give any errors,when i see in the database and in the php page only 0(zero) values are inserted in both,however time and id gets updated.please someone suggest me a proper code and way.
Try this:
<?php
$json_payload = json_decode($_GET['json_payload']);
$temp_value = $json_payload['temp_value'];
?>
When you do this:
r = requests.get('http://localhost/json1/js2.php',data=payload)
You are sending a get request containing a JSON string representation of your data:
'{"temp_value": 132}'
stored in the get parameter named json_payload.
Therefore, on the client side, you must retrieve the contents of the json_payload parameter and decode the JSON string therein in order to retrieve temp_value.
Alternatively, you could do this:
payload = {"temp_value":132}
r = requests.get('http://localhost/json1/js2.php',data=payload)
And leave your PHP code unmodified.
import json
import requests
data = {"temp_value":132}
data_json = json.dumps(data)
payload = {'json_playload': data_json}
r = requests.get('http://localhost/json1/js2.php',data=payload)
print(r.url)//http://localhost/json1/js2.php
Json data is not passed in to php.Check your python code
payload = {'key1': 'value1', 'key2[]': ['value2', 'value3']}
r = requests.get("http://httpbin.org/get", params=payload)
print(r.url)
Result:
http://httpbin.org/get?key1=value1&key2%5B%5D=value2&key2%5B%5D=value3
You have to use like
payload = {"temp_value":132}

Different JSON responses - {"count":"123"} vs {"count"=>"123"}

I have some PHP code which queries a MySQL database for a count.
When queried via a browser I get the following output:
{"count":"123"}
I also have a Ruby script which executes the same PHP script via Net::HTTP but the output is different:
{"count"=>"123"}
Why is this?
//The URL
uri = URI.parse("http://lab/count.php")
http = Net::HTTP.new(uri.host, uri.port)
//Request URL
request = Net::HTTP::Get.new(uri.request_uri)
//Basic authentication
request.basic_auth("user1", "secret")
response = http.request(request)
//Response
response = JSON.parse(response.body)
puts results
//Value 'count'
count = JSON.parse(response.body)[0]
puts count
Thanks.
{"count"=>"123"} is not JSON response.
It's ruby literal for Hash table.
I think you are seeing the result of parsed JSON:
>> require 'json'
>> JSON.parse('{"count":"123"}') # => {"count"=>"123"}
>> puts JSON.dump({"count"=>"123"}) # prints => {"count":"123"}
UPDATE response to comment
To get 123 printed.
uri = URI.parse("http://lab/count.php")
http = Net::HTTP.new(uri.host, uri.port)
request = Net::HTTP::Get.new(uri.request_uri)
request.basic_auth("user1", "secret")
response = http.request(request)
response = JSON.parse(response.body)
puts response['count']

php get curl posted data

I am calling a php api via curl
ncServerURL='http://myserver/acertify.php'
# binaryptr = open('sampleamex.xml','rb').read()
# print binaryptr
c = pycurl.Curl()
c.setopt(pycurl.URL, ncServerURL)
c.setopt(pycurl.POST, 1)
c.setopt(pycurl.SSL_VERIFYPEER, 0)
c.setopt(pycurl.SSL_VERIFYHOST, 0)
header=["Content-type: text/xml","SOAPAction:run",'Content-Type: text/xml; charset=utf-8','Content-Length: '+str(len(xmldata))]
# print header
c.setopt(pycurl.HTTPHEADER, header)
c.setopt(pycurl.POSTFIELDS, "xml="+str(xmldata))
import StringIO
b = StringIO.StringIO()
c.setopt(pycurl.WRITEFUNCTION, b.write)
c.perform()
ncServerData = b.getvalue()
return ncServerData
and posting xml data. in acertify.php and i am not able to xml data in php files , i am working on a project , what i don't know in this , how can i get curl posted data in this file .
<?php
echo "hi";
print_r($_SESSION);
print_r($_POST);
// print_r($_FILES);
?>
If you mean getting POST data in php, then at first glance looks like you are posting a single field c.setopt(pycurl.POSTFIELDS, "xml="+str(xmldata))
so it should just be $_POST['xml']
And if you mean reading data with curl as a response, then curl should have returntransfer option on execution (i'm not familiar with python syntax)

Categories