sending the json data from python to php - 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}

Related

Handling nested JSON POST requests in PHP

I am trying to have a python client send a post request which contains nested JSON like such
{"nested":{"field1":"response1", "field2":"response2"}}
My python code is here
from urllib.parse import urlencode
from urllib.request import Request, urlopen
url="http://localhost/api/vscore.php"
post_fields={"nested":{"field1":"response1", "field2":"response2"}}
request = Request(url, urlencode(post_fields).encode())
json = urlopen(request).read().decode()
print(json)
PHP code:
print_r($_POST["nested"]);
returns
{'field2': 'response2', 'field1': 'response1'}
but when I try to access "field1" with $_POST["nested"]["field1"], it returns this:
{
instead of returning "response1". How can I get my code to return fields in nested JSON?
If request is in json form then, you should json_decode it first and then try to access. nested key should be accessed as:
$nested = json_decode($_POST["nested"], true);
$field = $nested["field1"];

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'])

Send json data to php api through python

I am new to python. I have created a gui based app to insert values into database.
I have created a Rest api to handle db operations. How can i append the api URL with json created in python.
app.py
from Tkinter import *
import tkMessageBox
import json
import requests
from urllib import urlopen
top = Tk()
L1 = Label(top, text="Title")
L1.pack( side = TOP)
E1 = Entry(top, bd =5)
E1.pack(side = TOP)
L2 = Label(top, text="Author")
L2.pack( side = TOP)
E2 = Entry(top, bd =5)
E2.pack(side = TOP)
L3 = Label(top, text="Body")
L3.pack( side = TOP)
E3 = Entry(top, bd =5)
E3.pack(side = TOP)
input = E2.get();
def callfunc():
data = {"author": E2.get(),
"body" : E3.get(),
"title" : E1.get()}
data_json = json.dumps(data)
# r = requests.get('http://localhost/spritle/api.php?action=get_uses')
#url = "http://localhost/spritle/api.php?action=insert_list&data_json="
#
url = urlopen("http://localhost/spritle/api.php?action=insert_list&data_json="%data_json).read()
tkMessageBox.showinfo("Result",data_json)
SubmitButton = Button(text="Submit", fg="White", bg="#0094FF",
font=("Grobold", 10), command = callfunc)
SubmitButton.pack()
top.mainloop()
Error:
TypeError: not all arguments converted during string formatting
i AM GETTING error while appending url with data_json ?
There is an error on string formating:
Swap this:
"http://localhost/spritle/api.php?action=insert_list&data_json="%data_json
by this:
"http://localhost/spritle/api.php?action=insert_list&data_json=" + data_json
or:
"http://localhost/spritle/api.php?action=insert_list&data_json={}".format(data_json)
The following statements are equivalents:
"Python with " + "PHP"
"Python with %s" % "PHP"
"Python with {}".format("PHP")
"Python with {lang}".format(lang="PHP")
Also, I don't think sending JSON data like this via URL is a good idea. You should encode the data at least.
You are trying to use % operator to format the string, and you need to put the %s placeholder into the string:
"http://localhost/spritle/api.php?action=insert_list&data_json=%s" % data_json
Or use other methods suggested in another answer.
Regarding the data transfer - you definitely need to use POST request and not GET.
Check this, using urllib2 and this, using requests.

POSTing binary data over http with Python -> 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");

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