Handling JSON POST request in PHP - php

I am currently developing Android application, which will uses web services. I used PHP for backend. I am currently trying authentication via JSON to PHP. But I am stuck at some point, hope u guys will help.
I successfully write code to create JSON data in android also db connections in php using mysql, but i am confusing about how to handle JSON data. I am using POST request for sending JSON data.
I like to ask how i handle JSON data in PHP. More specific, I like to know how to grab POST request in PHP which contain JSON data??
Thanks in advance.
Thanking you.
EDIT:
I am using following code for sending POST request in android
HttpPost post = new HttpPost(address);
json.put("username", username);
json.put("password", pwd);
StringEntity se = new StringEntity("json"+json.toString());
Log.i(DEB_TAG, "The JSON Request is:"+json.toString());
se.setContentEncoding(new BasicHeader(HTTP.CONTENT_TYPE, "application/json"));
post.setEntity(se);
Log.i(DEB_TAG, "The post request is "+post.toString());
response = client.execute(post);
if(response != null){
InputStream in = response.getEntity().getContent();
Log.i(DEB_TAG, "The result is"+in.toString());
}
and using following code for parsing JSON request in php:
$string = $_POST['josnHeader'];
$obj = json_decode($string);
$username = $obj->{'username'};
$password = $obj->{'password'};
Is it correct or I am doing any wrong implementation??

Have you taken a look in your $_POST array in PHP?

$json = $_POST["var_name"];
$array = json_decode($json);

$json = $_REQUEST["your_param"];
$dtoObject = json_decode(stripslashes($json),true);

Related

Talking to PHP get commands from Android app

I have an android app and am trying to send data to the PHP on the server. The server gets the php data with
$this->get('uname');
$this->get('pass');
We do use codeigniter if that matters
The Java code, inside of an Async method, I currently have is
InputStream response = null;
URLConnection connection = new URL(urls[0]).openConnection();
connection.setRequestProperty("uname" , Username);
connection.setRequestProperty("pass", Password);
response = connection.getInputStream();
When I run this, the code always returns null but it is supposed to return a JSON array either way. I have checked the URL and it is correct. What am I doing wrong? Thanks!
You code should be like this
For your android side ,as mentioned by #Ichigo Kurosaki at Sending POST data in Android
For Codeigniter side , cosider you function name is user_login
function user_login(){
$uname = $this->input->get_post('uname'); //get_post will work for both type of GET/POST request
$pass = $this->input->get_post('pass');
$result=$this->authenticate->actLogin($uname,$pass ); //considering your authenticating user and returning 1,0 array as success/failure
$this->output
->set_content_type('application/json')
->set_output(json_encode($result));
exit;
}

android How to send POST json request to Laravel Framework

Hi im doing both android and laravel framework..
but when i do post method and send json to laravel api via POST.. it will give a 500 result.. please help..
this is one of my asynctask in android sending the post data.. assume sendJsonObj is a jsonobject with values..
URL url = new URL("http://dexter-laravelframe.rhcloud.com/register");
urlConnect = (HttpURLConnection) url.openConnection();
urlConnect.setRequestMethod("POST");
urlConnect.setConnectTimeout(10000);
urlConnect.setRequestProperty("Content-Type", "application/json");
urlConnect.setRequestProperty("x-csrf-token", Model_Application.token_csrf);
urlConnect.connect();
OutputStreamWriter outWrite = new OutputStreamWriter(urlConnect.getOutputStream());
outWrite.write(sendJsonObj.toString());
outWrite.flush();
outWrite.close();
int code = urlConnect.getResponseCode();`
on my Laravel framework..
routes.php
Route::post('/register', 'UserController#register');
UserController.php
public function register()
{
$json = Input::json()->all();
$resultJson = json_encode($json);
echo $resultJson;
}
this will give a 500 response code from Laravel api.. i want it to read the json data.. and send it back.. if i used Mozilla plugin rest client, and send the json data in body.. it gives 200..

decode json object sent form android app to php server

I am sending json object from android as such:
//Create JSONObject here
JSONObject json = new JSONObject();
json.put("key", String.valueOf(args[0]));
String postData=json.toString();
// Send POST output.
printout = new DataOutputStream(urlConn.getOutputStream ());
printout.writeUTF(URLEncoder.encode(postData,"UTF-8"));
Log.i("NOTIFICATION", "Data Sent");
printout.flush ();
printout.close ();
When it is sent to the server it looks like the following code snippet. ???%7B%22key%22%3A%22value%22%7D
I should add the first ??? are in a diamond each. When I decode the whole json object I get null. In the php server I have
$somevar=json_decode(json, true);
which returns null. Can someone point me on how to retrieve the json value? Thanks so much:)

Calling ASP.NET Web Api method with PHP

I have the following web method in my web api controller
public HttpResponseMessage PostMakeBooking(FacilityBookingRequest bookingRequest)
{
var returnStatus = HttpStatusCode.OK;
var json = new JavaScriptSerializer().Serialize(bookingRequest);
var response = Request.CreateResponse<CardholderResponse>(returnStatus, cardholderResponse);
return response;
}
When I make this call from my .NET app, my json string appears correctly when I seralize it
{"correlationId":null,"RequestId":"7ec5092a-342a-4e32-9311-10e7df3e3683","BookingId":"BK-123102","CardholderId":"123456","BookingFrom":"\/Date(1370512706448)\/","BookingUntil":"\/Date(1370523506449)\/","DeviceId":"ACU-01-R2","Action":"Add","LoginId":"tester","Password":"tester"}
However, when I made to call from my php script
public function web_request(){
$guid =self::getGUID();
$replace = array("{","}");
$guid = str_replace($replace, "", $guid);
$client = new Zend_Rest_Client("http://203.92.72.221");
$request= new myZendCommon_FacilityBookingRequest();
$request->RequestId =$guid;
$request->BookingFrom ="27/03/2013 05:30";
$request->BookingUntil ="27/03/2013 06:30";
$request->CardholderId ="E0185963";
$request->DeviceId ="ACU-B2-01-R1";
$request->BookingId ="111";
$request->Action ="Add";
$request->LoginId ="tester";
$request->correlationId ="(null)";
$request->Password ="tester";
$request = json_encode($request);
$response = $client->restPost("/ibsswebapi/api/facilitybooking",$request);
print_r($response);
exit();
The call goes to my web method, but when I serialize it using JavaScriptSerializer().Serialize(bookingRequest)
{"correlationId":null,"RequestId":null,"BookingId":null,"CardholderId":null,"BookingFrom":"\/Date(-62135596800000)\/","BookingUntil":"\/Date(-62135596800000)\/","DeviceId":null,"Action":null,"LoginId":null,"Password":null}
All the values are null.
Is something wrong with the script?
I believe Kiran is right. Not sure why some one has felt his answer is not useful. Anyways, my understanding is that you are creating a JSON string and doing a form post of the same. I guess in this case the content type is sent as application/www-form-urlencoded but request body is a JSON string. You can use Fiddler to see how the request is being sent by the PHP script. I don't have the PHP knowledge to tell you how you can post JSON but my guess is that if you just remove the JSON encoding line $request = json_encode($request);, it should be okay.
From ASP.NET Web API point of view, if the request has Content-Type: application/json header and the body has the right JSON or if the request has Content-Type:application/www-form-urlencoded header and the body has the form url encoded content like RequestId=7ec5092a-342a-4e32-9311-10e7df3e3683&BookingId=BK-123102 and so on, web API will absolutely have no problem in binding. Currently, the request is not being sent in the right format for web API to bind.
Are you sending the header Content-Type:application/json in your request?
Also add the following piece of code to catch any model state validation errors:
.
if (!ModelState.IsValid)
{
throw new HttpResponseException(
Request.CreateErrorResponse(HttpStatusCode.BadRequest, this.ModelState));
}

how to make PHP server sends data to an Android device

I want the Android device to send data to a PHP server. After receiving, the PHP server sends other data to Android. The first part can be done by using JSON. However, I don't know how to make the PHP server sends data to Android. Sorry, I am new to PHP!
I'm currently developing application that's communicating with PHP server (two-way communication, server sends data to application and application sends data to server), in objective-c [for iphone], but principle is same I guess.
We've used REST service with JSON.
In your case, it should work like this:
Mobile 1 sends data via REST call to REST server (it calls method1. Server is developed, for example, using Zend_REST.), it stores data in Database (mySQL for example).
Mobile 2 periodically sends request to REST server, to a method which checks for new entries in mySQL. If there's something new, it sends response with data, if not - it sends false.
Whatever data is "printed" by your PHP script will be returned in the response to the call made on the Android device.
You can do something like this in PHP:
<?php
// TODO: Handle incoming data
// Send JSON data back to client
header('Cache-Control: no-cache, must-revalidate');
header('Content-type: application/json');
// Compute data
$data = array(1, 2, 3, 4, 5, 6, 7, 8, 9);
// Encode/print data
echo json_encode($data);
?>
You would want to replace the first comment with your code to handle the data that was submitted from the client (Android). Then you set the response headers to be of type application/json and echo back your encoded data.
Technically you could echo/print back anything you would like, but using a format like JSON makes it much easier to decode the data on the client side.
Here is an Android snippet to send a POST request to some bogus website, sending email, password and a data string (you would put your json in the data string
HttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost("http://website.com/yourPageHere.php");
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
nameValuePairs.add(new BasicNameValuePair("email", emailString));
nameValuePairs.add(new BasicNameValuePair("password", passwordString));
nameValuePairs.add(new BasicNameValuePair("data", yourDataString));
try {
httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
} catch (UnsupportedEncodingException e) {
//do stuff
}
HttpResponse response = null;
try {
response = httpClient.execute(httpPost);
} catch (ClientProtocolException e) {
//do stuff
} catch (IOException e) {
//do stuff
}
if(response == null){
//time out or other problem, fail gracefully
}
HttpEntity responseEntity = response.getEntity();
try {
String jsonString = EntityUtils.toString(responseEntity);
//jsonString is the full body of the response from the server
//if your php script is sending json, thats whats in here
} catch (ParseException e) {
//do stuff
} catch (IOException e) {
//do stuff
}
Your php script, yourPageHere.php
Treat this just like any other php script you might write, except instead of returning html you are just returning a chunk of text representing json data.
<?php
header('Content-type: application/json');
/*
here you can use the $_POST['email'], $_POST['password']
and $_POST['data'] indexes to access the data sent to
you from the phone, then create a json string to return
to the phone
*/
/* you can convert php objects/arrays to json using
json_encode($object), handle this however you
want just so that $jsonString is the final
representation of the json object */
$jsonString = 'blabla';
/*
prints the string in the body of the response,
this is the "jsonString" object found in the
above android snippet.
*/
echo $jsonString; //
?>
You can do the above with GET requests instead of POST too.
If you are really new to PHP you might want to make a couple form page samples to get the hang of reading url parameters.
What you're looking for is some sort of AJAX call, allowing the HTTP GET request to stick around and wait for the server return value:
http://net.tutsplus.com/tutorials/javascript-ajax/5-ways-to-make-ajax-calls-with-jquery/

Categories