How to get the POST request entity using Slim framework - php

I have sent JSON data using android java by setting it in the post entity like this:
HttpPost httpPostRequest = new HttpPost(URLs.AddRecipe);
StringEntity se = new StringEntity(jsonObject.toString());
httpPostRequest.setEntity(se);
How can I receive this json data in the php , where I am using Slim framework ?
I have tried this:
$app->post('/recipe/insert/', 'authenticate', function() use ($app) {
$response = array();
$json = $app->request()->post();
});

JSON is not parsed into $_POST superglobal. In $_POST you can find form data. JSON you can find in request body instead. Something like following should work.
$app->post("/recipe/insert/", "authenticate", function() use ($app) {
$json = $app->request->getBody();
var_dump(json_decode($json, true));
});

You need to get the response body. Save it in a variable. After that, verify if the variable is null and then decode your JSON.
$app->post("/recipe/insert/", "authenticate", function() use ($app) {
$entity = $app->request->getBody();
if(!$entity)
$app->stop();
$entity = json_decode($entity, true);
});

Related

How do I return JSON data from CodeIgniter to Google Apps Script?

so we've been making a chatbot in Google Apps Script and one of its functions is to display information from a database (hosted online). The script sends a POST request to a controller function in our CodeIgniter program:
function do_post(name, status, duration) {
// Make a POST request with a JSON payload.
var data = {
'name': name,
'status': status,
'key' : api_key,
'duration' : duration
};
var options = {
'method' : 'post',
'contentType': 'application/json',
'muteHttpExceptions' : true,
// Convert the JavaScript object to a JSON string.
'payload' : JSON.stringify(data)
};
var response = UrlFetchApp.fetch('https://www.domainname.com/bot/index.php/bot/process/', options);
Logger.log(response);
return response;
}
The function above successfully inserts a record into the database using our process() controller in CI, but the problem is in our response variable. It's of HttpResponse type and we don't know how to return that type from our controller. We want our controller to return something like {"Response": "success"} to our chatbot but we don't know how. We've tried returning a JSON-encoded array:
public function process()
{
$_POST = array_replace($_POST, json_decode(file_get_contents('php://input'), true) ?? []);
$name = $_POST["name"];
$status = $_POST["status"];
$api = $_POST["key"];
$duration = $_POST["duration"];
if ($api == api_key){
$result = $this->bot_model->add_log();
}
$res_array = array("response" => $result);
// encode array to json
$json = json_encode($res_array);
return ($json);
}
}
And we try accessing var response in our app script using response.getContentText(), but we get something like "string(39)" and then the value of our api_key. How do we access the json data from the response?
You need to set the mime-type of your page so you can serve JSON data by using the set_content_type() method from the Output class.
Check the code
public function process()
{
$_POST = array_replace($_POST, json_decode(file_get_contents('php://input'), true) ?? []);
$name = $_POST["name"];
$status = $_POST["status"];
$api = $_POST["key"];
$duration = $_POST["duration"];
if ($api == api_key){
$result = $this->bot_model->add_log();
}
// JSON OUTPUT
$this->output
->set_content_type('application/json')
->set_output(json_encode( array("response" => $result)));
}
I noticed that when a function in CodeIgniter is called via post, the return of that function is whatever is printed out by the function in any way, be it echo, print_r, or var_dump. So to return your JSON file to App Script simply do echo $json;.

Why my request POST swift to php, the content always to be key in PHP

This is my first time, try swift to rest API PHP, i try request POST to PHP, but the key and value i request always to be key in php
i had try in swift 5, php 7
this is code in my swift:
func getTimeline(completion: #escaping (Result<MainResponse<String>, Error>) -> Void) {
var param: [String: Any] = [:]
param["device_id"] = UIDevice.current.identifierForVendor?.uuidString
param["X_SIGNATURE_API"] = "X-secure"
param["name"] = "Rangga Leo"
let url = URLConst.server
HTTPRequest.shared.connect(url: url, params: param, model: String.self) { (result) in
completion(result)
}
}
this is my URL ngrok if you want try : https://d9422a31.ngrok.io
anyway i have to create my own class to make dataTask more reuseable, and than this is simple response in my PHP :
header("Content-Type: application/json");
$data = [
"POST" => $_POST,
"device_id" => $_POST["device_id"]
];
echo json_encode($data);
i expect the result show my device_id, but in case php given null value, event i debug $_POST, device_id is available but to be key in array PHP
btw, this is result in my console
{
"POST":{"{\"X_SIGNATURE_API\":\"X-secure\",
\"name\":\"Rangga_Leo\",
\"device_id\":\"C3E259A9-FBEB-4D65-9B6A-EC4F8BE89D95\"}":""},
"device_id":null
}
You can try bellow code to get json payload
$dataPayload = json_decode(file_get_contents('php://input'), true);
print_r($dataPayload);
echo $dataPayload["device_id"];
or put this line to above of the line create data structure
$_POST = json_decode(file_get_contents('php://input'), true);
It looks like you are sending a JSON object in the POST.
To read it from php you can replace your code with
header("Content-Type: application/json");
$decoded_data = json_decode($_POST);
$data = [
"POST" => $_POST,
"device_id" => $decoded_data["device_id"]
];
echo json_encode($data);

API callback response

I'm using an API to send sms in my codeigniter project. After sending, it will return a response array in the form of json to a callback url in my project. And i need to update this response in my database. Here is my code :
the response array will be similar as follows :
{"req_id":"809ff62f-74a9-45a5-9cb5-5e60763289af","status":"0" ,"comment":"OK"}
my callback url redirects to following function in my controller
public function templateCallback() {
$json = file_get_contents('php://input');
$json = urldecode($json);
$obj = json_decode($json, TRUE);
$reqID = $obj->req_id;
$status = $obj->status;
print_r($obj);
$this->db->where('TemplateRequestID', $reqID);
$this->db->set('TemplateApproved', $status);
$this->db->update('templatemaster_tbl');
}
But its never get updated. What is wrong in my code ? I'm not good in json. So i'm not sure is this the correct way to fetch and decode json array in php. Someone please help me.
To test this i have created a view in my project and send this same array through an ajax function like :
var base_url = '<?php echo base_url()?>';
$('#test').click(function() {
var val = $('#testvalue').text();
$.ajax({
type: 'post',
url: base_url + 'API/templateCallback',
data: {
val
},
success: function (response) { console.log(response);
}
});
});
and try to print both $json and $obj in controller function.
$json displays a string like : val=%7B%22req_id%22%3A%228b3eef97-330a-4271-8450-0676fbac8885%22%2C%22status%22%3A%220%22%2C%22comment%22%3A%22OK%22%7D
and $obj displays nothing
If your $json contains encoded value (%7B%22req_id%22%3A%228b3eef97-330a-4271-8450-0676fbac8885%22%2C%22status%22%3A%220%22%2C%22comment%22%3A%22OK%22%7D) you should decode it first with urldecode.
So proper code would be:
...
$jsonEncoded = file_get_contents('php://input');
$json = urldecode($jsonEncoded);
$obj = json_decode($json, TRUE);
...

Get params from angular $http in Codeigniter controller

I am new to angular.So i dont know i am doing it in the right way.I am working in codeigniter along with angular.I need to get the id which i was passing though the angular $http service in my codeigniter controller.. I didn't get any console errors. Simply the data is not returning.. This is my angular controller
app.controller("newsController_id",function($scope,$http,$routeParams){
$http({ method:'POST',
url:'Controller1/get_list_id',
params:{id:$routeParams.id}
})
.then(function (response) {
$scope.blogs_id = response.data;
})
codeigniter controller
public function get_list_id() {
$id=$this->input->post('id');
//$id='6';
$data = $this->Blog_model->getAll_id($id);
$this->output->set_content_type('application/json')->set_output(json_encode($data));
}
There are no errors in the codeigniter model and view pages..since i got my result perfectly when i hardcoded the id value as 6.But no output when i posting the id.help me solving this
you are doing wrong way to pass data angujarjs to codeigniter.
if you want to pass data in POST method pass object in $http service on data section like below
AngularJS Code
$http({
method:'post',
url:'/login',
dataType:"json",
data:{"vEmail":$scope.vEmail,"vPassword":$scope.vPassword},
}).then(function(suc){
console.log(suc);
},function(err){
console.log(err);
});
Codeigniter Code
$vEmail = $this->input->post('vEmail');
$vPassword = $this->input->post('vPassword');
If you want to pass data usgin GET you should be pass data in Param section like below
$http({
method:'get',
url:'/login',
dataType:"json",
params:{"vEmail":$scope.vEmail,"vPassword":$scope.vPassword},
}).then(function(suc){
console.log(suc);
},function(err){
console.log(err);
});
you can get that in codeigniter using get method like below
$this->input->get('vEmail');
You can not get the data by $_POST or $this->input->post , You should have something like this in constructor:
$postdata = file_get_contents("php://input");
$this->request = json_decode($postdata);
Now In controller, you can access the id:
$id = $this->request->id;
But it has a problem, you can't use Codeigniter form validation, because it works with $_POST superglobal. You can do something like this instead (in constructor):
$objectRequest = json_decode( file_get_contents("php://input") );
$this->request = xss_clean( json_decode(json_encode($objectRequest), true) );
$_POST = $this->request;
But this time you can access to id by the following example:
$id = $this->request['id'];
in order to get the post variables from angular you need use the following code
$postdata = file_get_contents("php://input");
$myData = json_decode($postdata);
instead of $id=$this->input->post('id');
so your $id = $myData->id;
Your final code would look like this:
public function get_list_id() {
$postdata = file_get_contents("php://input");
$myData = json_decode($postdata);
$id = $myData->id;
//$id='6';
$data = $this->Blog_model->getAll_id($id);
$this->output->set_content_type('application/json')->set_output(json_encode($data));
}

Generating alternate JSON for jstree using php

I am trying to generate generate Alternate JSON code for jstree in my PHP controller.
I am creating what looks like the correct data, however, jstree does not display it.
My javascript looks like this:
$this->registerJs("
$(function() {
$('#statustree').jstree({
'core' :
{
'data' :
{
'datatype' : 'json',
'url' : '/myaccount/buildstatustree',
}
}
});
$('#statustree').on('loaded.jstree', function()
{
$('#statustree').jstree('open_all');
});
})
", \yii\web\VIEW::POS_READY);
and my php looks like this:
// convert to JSON format for jstree
$tree = array();
$parent = new stdClass();
$parent->id = 'P1';
$parent->parent = '#';
$parent->text = $username;
$tree[] = $parent;
$student1 = new stdClass();
$student1->id = 'S1';
$student1->parent = 'P1';
$student1->text = 'Poly';
$tree[] = $student1;
$student1 = new stdClass();
$student1->id = 'S2';
$student1->parent = 'P1';
$student1->text = 'Bob';
$tree[] = $student1;
// convert to json and send
header('Content-type: application/json');
return json_encode( $tree );
My controller is getting called and is returning a string that looks like this:
[
{"id":"P1","parent":"#","text":"user2"},
{"id":"S1","parent":"P1","text":"Poly"},
{"id":"S2","parent":"P1","text":"Bob"}
]
The spinner spins while the call is made, but the spinner disappears, and my tree is not displayed...
I suspect that I am not forming my Alternate JSON response correctly, but nothing I try works....
Thanks
-John
The data you are generating looks fine (provided that is what you see in your dev tools as the response to the AJAX call that jsTree makes).
You might want to check if all the headers are OK - is it really served as JSON? You can also try adding the charset just in case:
header('Content-Type: application/json; charset=UTF-8');
I see you are already trying to force jQuery to treat the response as JSON regardless of headers, but use "dataType" instead of "datatype".
If this does not work - please share what you see in the net panel of your developer console - the headers and the response to the AJAX call jsTree makes.

Categories