Receive JSON object from HTTP Get in PHP - php

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.

Related

How can I create a RESTfull service to retrieve a json or xml file from a client

I have to write a RESTfull service in PHP which can send json data to the caller and retrieve json (or xml) data from the user. I know how to send json or xml data, but not how I can get data back from the user.
The simplest way is getting JSON data as POST or PUT body. To get PHP body:
$entityBody = file_get_contents('php://input');
and then decode json into a PHP object:
$requestBody = json_decode ( $entityBody);
If you are not sour the request body is XML or JSON then check Content-Type in the header.
A RESTful api usually doesnt expect a "response" from the client.
What you want to do is to create an endpoint for the client to POST the specific content.
/api/user/?json={...}
On the PHP side you can retrieve the data with $_REQUEST['json'] (which includes both POST and GET.
There is something called HATEOS that can be used for telling the client about links associated with the current resource (if you want to "chain" calls between the client and the service).

Get and Send file with PHP and RESTful API

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/

PHP Unirest plugin not working properly

I use Unirest for PHP to do some HTTP Requests. Everything works fine, until I want to pass a fairly complex JSON to my Node.js router.
First I do a GET request that returns a JSON Object, then I extend this JSON object (needs to be done, I know it sucks) and want to feed it back into my other http POST request... and here is where the trouble starts:
I echoed the JSON that is returned and copied the output into postman -> works fine. If I want use the JSON directly in PHP in next request:
$teamsMemberOf is the variable which is containing the GET response.
$headers = array("Accept" => "application/json");
$newBody = '{"team":'.$teamsMemberOf->raw_body.'}';
$relevantBoxesAmount = Unirest\Request::post("http://localhost:3001/my/route/".$result['_id']."/get-something-from-server", $headers, $newBody);
and it doesn't work.
Error is 500 and 'Cannot read property '0' of undefined' which is certainly related to something in the JSON object.
Does someone have an idea how to fix it?

Can't read raw POST body data - how to do this in this example?

I'm setting an API for my server for another developer. I'm currently using Flash AIR to send POST data to my server, and simply extract the variables as in
$command = $_POST['command'].
However, he's not using Flash, and is sending data like so:
https://www.mysite.com POST /api/account.php?command=login HTTP/1.1
Content-Type: application/json
Connection: close
command=login
params {"pass":"12345678","token":"","appID":"theirApp","user":"johnnyb","ver":"2.0","Library_ID":"1"}
My server is returning him an error saying that the 'command' parameter is missing.
What do I need to do my end to extract the $_POST var 'command' from his above data?
I've tried file_get_contents('php://input') and http_get_request_body(), but although they don't error, they don't show anything.
Thanks for your help.
The request claims that it is sending JSON.
Content-Type: application/json
However, this:
command=login
params {"pass":"12345678","token":"","appID":"theirApp","user":"johnnyb","ver":"2.0","Library_ID":"1"}
… is not JSON.
If you get rid of everything before the { then it would be JSON and you should be able to read it with file_get_contents('php://input') (and could then pass it through a decoder.
I've tried file_get_contents('php://input') and http_get_request_body() … they don't show anything.
They should work.
When I print out file_get_contents('php://input') for the comms … I get command=login, yet...
I thought you said you didn't get anything
if(!isset($_POST['command']))
$_POST will only be populated for the two standard HTML form encoding methods. If you are using JSON then it won't be automatically parsed, you have to do it yourself (with valid JSON input (so the additional data would need to be encoded in the JSON text with the rest of the data)), file_get_contents('php://input') and decode_json).
"Content-Type should be www-form-urlencoded" from #Cole (correct answer)
More info here: http://www.w3.org/TR/html401/interact/forms.html#h-17.13.4.1
The command parameter needs to be part of the data, and the whole thing should be valid JSON. As is, command=login, it is not valid JSON.
Add it to the params object or make a containing object, like
{
command:'login',
params :{"pass":"12345678","token":"","appID":"theirApp","user":"johnnyb","ver":"2.0","Library_ID":"1"}
}

Use JSONP without wrapping response

My server outputs this JSON when I put the URI in web browser. My client app will get this JSON using JSONP because it accesses the foreign domain.
{
"is_execution_successful":true,
"data": "something"
}
Is there a way to do a JSONP without wrapping the response like this:
echo $_GET['json_callback']. '('. json_encode($rtnjsonobj) . ')';
I don't have permission to edit the server output. How to get the JSON using AJAX/JQuery?
Reference I read: http://remysharp.com/2007/10/08/what-is-jsonp/
JSONP has technically nothing to do with JSON. It's simply javascript code.
So if the response is valid JSON, it will not do anything useful when you run it as javascript (JSONP). Especially in this case, the JSON causes a syntax error when executed as javascript.
You can make cross-origin ajax request to the resource, but this is only possible if the server sends this header:
Access-Control-Allow-Origin: *
The star can be replaced with your specific origin of course, it doesn't have to be a wildcard

Categories