php get curl posted data - php

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)

Related

Passing variables from php to python and python to php

I am breaking my head to make this work but I am in a dead end. I have no idea what I am doing wrong.
I play with php and python; trying to execute a python script through php exec(), return an output and pass it to another python script.
This is my workflow:
1) Through jquery and an ajax request I pass some data to a php file (exec1.php) which looks like this:
$number = $_POST['numberOfClusters'];
$shape = $_POST['shapeFilePath'];
// EXECUTE THE PYTHON SCRIPT
$command = "python ./python/Module1.py $number $shape";
exec($command,$out,$ret);
print_r($out);
print_r($r); //return nicely 1.
2) The python file which I run Module1.py looks like this:
# this is a list of list of tuples
cls000 = [[(365325.342877, 4385460.998374), (365193.884409, 4385307.899807), (365433.717878, 4385148.9983749995)]]
# RETURN DATA TO PHP
print cls000
3) Then I have a nested AJAX request inside the success function of my previous AJAX request in which I pass the response (in this case the cls000 list) into a php script called (exec2.php) like this:
# PASS VARIABLES FROM FORM
$number = $_POST['numberOfClusters'];
$shape = $_POST['shapeFilePath'];
$clusterCoords = $_POST['response']; # response from previous Ajax request
// EXECUTE THE PYTHON SCRIPT
$command = "python ./python/Module2.py $number $shape $clusterCoords";
exec($command,$out,$ret);
print_r($out); ## THIS GIVES ME AN EMPTY ARRAY!!
print_r($ret); ## THIS GIVES ME A RETURN STATUS: 2
4) My Module2.py script looks like this:
number = int(sys.argv[1])
shape = sys.argv[2]
cls000 = json.loads(sys.argv[3])
# RETURN DATA TO PHP
print cls000
What am I doing wrong? If I remove this line 'cls000 = json.loads(sys.argv[9])' and return for example 'shape' everything works fine. But when I try to return cls000 I get a status code 2.
What am I missing here?

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

I have to pass an array from a php file to python file but my code is giving output NULL

PHP code:
<?php
$data = array('1','4','67','34');
$result = shell_exec('C:/Python27/python C:/xampp/htdocs/123.py ' . escapeshellarg(json_encode($data)));
$resultData = json_decode($result, true);
var_dump($resultData);
?>
Python Code:
import sys, json
# Load the data that PHP sent us
try:
data = json.loads(sys.argv[1])
except:
print "ERROR"
sys.exit(1)
# Generate some data to send to PHP
result = {'23','4'}
# Send it to stdout (to PHP)
print json.dumps(result)
There is incorrect data for json.dump() in Python
# Generate some data to send to PHP
result = {'23','4'}
So this give error, not json string
import sys, json
# Generate some data to send to PHP
result = {'23','4'}
# Send it to stdout (to PHP)
print json.dumps(result)
and PHP get NULL as $result from Python so you get NULL on screen - in browser
Use (for example):
# Generate some data to send to PHP
result = {'a':'23','b':'4'}
and json.dump() will work fine.
Add 2>&1 (stdout & stderr) behind the command like so:
$result = shell_exec('C:/Python27/python C:/xampp/htdocs/123.py ' . escapeshellarg(json_encode($data)) . ' 2>&1');

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");

Categories