I have an internal server that is generating JSON every few minutes. I need to pass this to and external server so I can manipulate the data and then present it in web interface.
Here is my python that send the data to PHP script:
x = json.dumps(data)
print '\nHTTP Response'
headers = {"Content-type": "application/json"}
conn = httplib.HTTPConnection("myurl.com")
conn.request("POST", "/recieve/recieve.php", x, headers)
response = conn.getresponse()
text = response.read()
print "Response status: ",response.status,"\n",text
conn.close()
and Here is my PHP to receive the data
$data = file_get_contents('php://input');
$objJson = json_decode($data);
print_r ($objJson);
My python script return with response status 200 which is good and it returns my JSON. But on the PHP side I want to be able to store this information to manipulate and then have a web client grab at it. However it appears that even if I say
print_r ($objJson);
when I visit the .php page it does not print out my object. I suppose the data is gone because file::input will read only and then end?
Don't use file_get_contents()
Just:
if($_POST){ echo "WE got the data"; }
and print_r will help you with where to go from there, if you are unfamiliar with PHP arrays.
Try to use named parameter containing your JSON data while sending data to PHP and try to use the $_POST superglobal array in PHP (because you obviously connecting via cgi or similar interface not via cli).
You can see all the POST data by printing your $_POST array:
print_r($_POST);
Here is what I did in the end as a quick fix
the python
x = json.dumps(data)
headers = {"Content-type": "application/json"}
conn = httplib.HTTPConnection("myurl.com")
conn.request("POST", "/script.php", x, headers)
response = conn.getresponse()
text = response.read()
print "Response status: ",response.status,"\n",text
conn.close()
then I realized that the PHP was receiving the post data but I was having a hard time manipulating it. So I just sent the JSON to a receiving PHP file that wrote the data as file and then has another JavaScript request grab that.
the php
if($_POST){ echo "WE got the data\n"; } //thanks rm-vanda
$data = file_get_contents('php://input');
$file = 'new.json';
$handle = fopen($file, 'a');
fwrite($handle, $data);
fclose($handle);
exit;
Then from my client just a ajax request for the file and parsed it on the client side.
Eventually I have to rethink this but it works for now. I also have to rewrite over the new.json file each time new data comes in or parse the old data out on the JavaScript success callback. Depends what you want to do.
Related
I'm trying to get Tradingview signals to my remote php script using webhook and trading view alerts. I can't succeed . I'm following this way
In my trading view strategy I have this
strategy.entry("Long", strategy.long, alert_message = "entry_long")
strategy.exit("Exit Long", "Long", limit=LONG_take_profit, stop=LONG_stop_loss, alert_message = "exit_long")
then I set the alert as follow
Then I set a PHP script as follow to receive the POST curl JSON data from Trading view
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
// fetch RAW input
$json = file_get_contents('php://input');
// decode json
$object = json_decode($json);
// expecting valid json
if (json_last_error() !== JSON_ERROR_NONE) {
die(header('HTTP/1.0 415 Unsupported Media Type'));
}
$servdate2 = time();
$servdate=date('d-M-Y H:i:s',$servdate2);
file_put_contents("/home/user/public_html/data.txt", "$servdate :".print_r($object, true),FILE_APPEND);
}
I receive the alert via email correctly but I do not receive data in /home/user/public_html/data.txt . What am I doing wrong ? How to send the Tradingview JSON data to my remote PHP script ?
I'm not familiar with PHP, but you've asked:
How to send the Tradingview JSON data to my remote PHP script ?
Your alert message as it is currently written in the alert_message argument, is not valid JSON and therefore it is sent as a txt/plain content type. If you want the alert to be sent as application/json you will need to have it in a valid JSON.
Webhooks allow you to send a POST request to a certain URL every time the alert is triggered. This feature can be enabled when you create or edit an alert. Add the correct URL for your app and we will send a POST request as soon as the alert is triggered, with the alert message in the body of the request. If the alert message is valid JSON, we will send a request with an "application/json" content-type header. Otherwise, we will send "text/plain" as a content-type header.
You can read more about it here.
EDIT:
You can make minor adjustments to your code, and it will be sent as JSON:
strategy.entry("Long", strategy.long, alert_message = '{"message": "entry_long"}')
strategy.exit("Exit Long", "Long", limit=LONG_take_profit, stop=LONG_stop_loss, alert_message = '{"message": "exit_long"}')
Replace the script with:
<?php
file_put_contents("/home/user/public_html/data.txt", print_r([$_GET, $_POST, $_SERVER], true));
to better understand the incoming data.
Maybe the data are present in $_POST variable, if not, post the whole result here (via pastebin).
(also make sure the PHP script starts with <?php)
I have an apache2 server and php file to receive json via POST in my php code like this
$json = json_decode(file_get_contents('php://input'), true);
$mac_ = $json["code"];
$userId_ = $json["msg"];
and saving it to mysql. This work when I send post via python's requests but not when I'm recieving data from API android device. - When I look at the apache log file, there is a connection, so I'm assuming that some data are received, but because I can't touch that API android device I'm not sure if this part $json["code"] has a right parameter. I would like to know a way to save somewhere all recieved data from this part
$json = json_decode(file_get_contents('php://input'), true);
because I can't check it by echo or so
One of my partners has an API service which should send an HTTP POST request whenever a new file is published. This requires me to have an api file which will get the POST this way:
http://myip:port/api/ReciveFile
and requesting that the JSON format request should be:
{
"FILE ":"filename.zip",
"FILE_ID":"123",
"FILE_DESC":"PRUPOUS_FILE",
"EXTRAVAR":"",
"EXTRAVAR2":"",
"USERID":" xxxxxxxxxxxx",
"PASSWORD":"yyyyyyyyyyy"
}
Meanwhile it should issue a response, in JSON format if it got the file or not
{"RESULT_CODE":0,"RESULT_DESCR":""}
{"RESULT_CODE":1001,"RESULT_DESCR":"Bad request"}
And after, when I am finished elaborating the file, I should send back the modified file same way.
The question is, now basically from what I understand he will send me the variables witch I have to read, download the file, and send a response back.
I am not really sure how to do this any sample code would be welcomed!
I'm not sure exactly what the question is, but if you mean creating a success response in JSON for if an action occurred while adding data to it which is what can be understood from the question, just create an array with the values you wish to send back to the provider and do json_encode on the array which should create json and just print it back as a response.
About receiving the information; all you have to do is use the integrated curl functions or use a wrapper (Guzzle, etc) to output the raw JSON or json_decode data into a variable and do whatever you please with it.
From what I read in the question, you wish to modify the contents of it. This can be achieved by just decoding the json and changing the variables in the array, then printing the modified JSON back as a response.
Example (this uses GuzzleHTTP as an example):
$res = $client->request('GET', 'url');
$json = $res->getBody();
$array = json_decode($json, 1); // decode the json
// Start modifying the values or adding
$array['value_to_modify'] = $whatever;
$filename = $array['filename']; // get filename
// make a new request
$res = $client->request('GET', 'url/'.$filename);
// get the body of specified filename
$body = $res->getBody();
// Return the array.
echo json_encode($body);
References:
http://docs.guzzlephp.org/en/latest/
I have a python script which succesfully posts a file to my localhost webserver running apache in <100ms. Now, I want to do exactly the same with Lua. I have come up with a script that posts that same image to my webserver but it takes a whopping ~24s to complete. The php running on the server receives and stores the file properly but for the Python script, the file comes in the $_FILES array whereas for the Lua script, I have to copy content from the php://input stream - also, looking at both POST requests with wireshark, I can see a 7667 POST from the Python script but not from the Lua, instead only a few TCP SYN & ACK frames. Any idea why my Lua script is missing the actual POST (incl. url) but it still seems to work (but really slow):
Some code is below:
Python
#!/usr/bin/python
import urllib2
import time
from binascii import hexlify, unhexlify
import MultipartPostHandler
fname="test.gif"
host = "localhost"
#host = "semioslive.com"
URI="/test.php"
#URI="/api/gateway.php"
nodemac ="AABBCC"
timestamp = int(time.time())
func="post_img"
url = "http://{0}{1}?f={2}&nodemac={3}&time={4}".format(host, URI,func,nodemac,timestamp)
opener = urllib2.build_opener(MultipartPostHandler.MultipartPostHandler)
data = {"data":open(fname,"rb")}
#r.get_method = lambda: 'PUT'
now = time.time()
response = opener.open(url, data, 120)
retval = response.read()
if "SUCCESS" in retval:
print "SUCCESS"
else:
print "RESPONSE sent at "+retval
print " Now "+str(time.time())
print "Request took "+str(time.time()-now)+"s to return"
Lua
#! /usr/bin/lua
http = require("socket.http")
ltn12 = require("ltn12")
local request_body = ltn12.source.file(io.open("test.gif"))
local response_body = {}
http.request{
url = "`http://localohst/test.php`",
method = "POST",
headers = {
["Content-Type"] = "multipart/form-data",
["Content-Length"] = 7333
},
-- source = ltn12.source.file(io.open("test.gif")),
source = request_body,
sink = ltn12.sink.table(response_body)
}
print(response_body[1]) --response to request
PHP
<?
if (isset($_FILES['data']))
move_uploaded_file($_FILES['data']['tmp_name'],"post(python).gif");
else
copy("php://input","post(lua).gif");
echo "SUCCESS!";
?>
Make sure your Lua script is sending the same HTTP headers. The important part for PHP is that the form with attached file upload is sent as "multipart/form-data", and the file must be properly embedded in the POST body of the HTTP request as a multipart mime message.
I cannot see if your Lua script actually does this, but I think no. Otherwise PHP would be happy.
I am trying to implement a php client that sends an HTTP GET to the server which sends back a JSON object with the return information. I know how to decode the JSON once my php script has received it, but how would I go about actually getting it?
EDIT: Note - I send the server an HTTP GET, and it generates and sends back a JSON file. It is not a file sitting on the server.
Check out file_get_contents
$json = file_get_contents('http://somesite.com/getjson.php');
Browsers act differently based on what the server responds. It does not matter what type of request you make to the server (be it GET, POST, etc), but to return JSON as a response you have to set the header in the script you make the request to:
header('Content-Type: application/json;charset=utf-8;');
And then echo the JSON string, for example:
//...populating your result data array here...//
// Print out the JSON formatted data
echo json_encode($myData);
User agent will then get the JSON string. If AJAX made the request then you can simply parse that result into a JavaScript object that you can handle, like this:
//...AJAX request here...//
// Parse result to JavaScript object
var myData=JSON.parse(XMLHttp.responseText);
The header itself is not -really- necessary, but is sort-of good practice. JSON.parse() can parse the response regardless.