How to decode JavaScriptSerializer object in php - php

My goal is to send request from asp.net's page to php's page, and send email from php page.
my code on asp.net's page is
Dictionary<string, string> keyValues = new Dictionary<string, string>();
keyValues.Add("to", "to#gmail.com");
keyValues.Add("from", "from#gmail.com");
keyValues.Add("message", "Conent of Email");
keyValues.Add("Subject", "Subject of Email");
JavaScriptSerializer js = new JavaScriptSerializer();
string json = js.Serialize(keyValues);
WebClient webClient = new WebClient();
NameValueCollection formData = new NameValueCollection();
formData.Add("a", json);
byte[] response = webClient.UploadValues("http://example.com/emailme.php", "POST", formData);
string responsebody = Encoding.UTF8.GetString(response);
the value which i'm passing after Serializing is
and the code written in my php page is
if (isset($_POST['a']))
{
echo "Value Exists";
echo "<br> Value before decoding is ".$_POST['a']."<br>";
$result=json_decode($_POST['a'],true);
echo "the value after decoding is ";
echo $result;
echo "<br> now for print_r <br>";
print_r($result);
} else
{echo "Value Does Not Exists";}
it was the code, now i'm attaching the image of result for my request.
As you can see the it shows the result before decoding for after decoding it shows nothing.
i will proceed for sending email after the result.

$result=json_decode(stripslashes($_POST['a']),true);
will do the trick ;)

Related

Converting PHP response string to JSON in Android, always says JSON string is Malformed

I am trying to send data from MSSQL table on server to Android app via PHP. I am using Volley to send the request for data.
The issue is that no matter what I try, Android says the returned JSON encoded string is "Malformed".
I have put the returned JSON string "response" into online JSON decoders and it displays perfectly, yet Andoid says: "Syntax error, malformed JSON{"data":[{"claimNumber":"f265e5e.....}]".
However, if I hardcode a copy and paste of the returned "response" string into a variable "input" in the Android
response function, it works perfectly.
JSONObject jObj = new JSONObject(response); ** Fails - Android says Malformed.
JSONObject jObj = new JSONObject(input); ** Android uses it with no issues.
The following is the method in Android used to receive the PHP response. Have included Log outputs of both the "response" string and
the manually entered "input" string. They are identical, yet Android won't use the actual "response" string.
public void onResponse(String response) {
if (response.equals("failed")) {
Log.d("failed", "failed");
callback.onResponse(null);
return;
}
try {
// Android sees the response returned from the PHP function as always Malformed.
Log.d("response", response);
D/response: - Syntax error, malformed JSON {"data":[{"claimNumber":"f265e5e6513070abd1f711232cfd3a491075f15bc9714cf723e373f02e71a214","xlsLine":"8b3490231cd923c133989dd93574de131b6c388a86153a74eb6ae2507193a008c9d3d0264452cc1bd1113d5a722f3ea7975f322461f486be96e789424459e20bcbaf878f5d0efe09426b90c046d881100e166ef0bfcf8721266383aabf3837a213854e8425e92b722791640576d3c0ce7722ff3de2e6005c85df840bea3b10982b7bcf8bec3398ea03e08e6a2879cb29e0e6c3c05370e1c2cf819e6156991c762b2247e8a5b51edb852bb371aca011eccaa581ed577e74d6bf0f2a71e43e7751e3fa6e5f68c2a6e4ccd4fc338fc2a2ea4a9d98018c52fe5953741a53d7f7a6f1c1e57901d64c957dc1776ab0ed28f5754f7d44008ebc5864cfd34dd3b1f1bf82db49674b8e7a3e381882f7cc1035bfdba114280f6c173e337d1813fb47a9b1aaf1d52faac197f90cced9eea754cf441cb262b3117444ad3a265cefb9593d40cdb8a3ae0235cc06baffbcac493bf45852908b014f063c29d85347e808e7ed4be8688327bf3280759ea1ff187287dcabaaee8859a6da782cd2451e2911fe16ca7d","markerColor":"0","edited":"0"}]}
// If I copy the returned "response" string manually into a variable "input", Android says it's fine.
String input = "{\"data\":[{\"claimNumber\":\"f265e5e6513070abd1f711232cfd3a491075f15bc9714cf723e373f02e71a214\",\"xlsLine\":\"8b3490231cd923c133989dd93574de131b6c388a86153a74eb6ae2507193a008c9d3d0264452cc1bd1113d5a722f3ea7975f322461f486be96e789424459e20bcbaf878f5d0efe09426b90c046d881100e166ef0bfcf8721266383aabf3837a213854e8425e92b722791640576d3c0ce7722ff3de2e6005c85df840bea3b10982b7bcf8bec3398ea03e08e6a2879cb29e0e6c3c05370e1c2cf819e6156991c762b2247e8a5b51edb852bb371aca011eccaa581ed577e74d6bf0f2a71e43e7751e3fa6e5f68c2a6e4ccd4fc338fc2a2ea4a9d98018c52fe5953741a53d7f7a6f1c1e57901d64c957dc1776ab0ed28f5754f7d44008ebc5864cfd34dd3b1f1bf82db49674b8e7a3e381882f7cc1035bfdba114280f6c173e337d1813fb47a9b1aaf1d52faac197f90cced9eea754cf441cb262b3117444ad3a265cefb9593d40cdb8a3ae0235cc06baffbcac493bf45852908b014f063c29d85347e808e7ed4be8688327bf3280759ea1ff187287dcabaaee8859a6da782cd2451e2911fe16ca7d\",\"markerColor\":\"0\",\"edited\":\"0\"}]}";
// Log showing Androids interpretation of the manually entered "input" string
// It matches the "response" string exactly yet "response" string fails.
Log.d("input", input);
D/input: {"data":[{"claimNumber":"f265e5e6513070abd1f711232cfd3a491075f15bc9714cf723e373f02e71a214","xlsLine":"8b3490231cd923c133989dd93574de131b6c388a86153a74eb6ae2507193a008c9d3d0264452cc1bd1113d5a722f3ea7975f322461f486be96e789424459e20bcbaf878f5d0efe09426b90c046d881100e166ef0bfcf8721266383aabf3837a213854e8425e92b722791640576d3c0ce7722ff3de2e6005c85df840bea3b10982b7bcf8bec3398ea03e08e6a2879cb29e0e6c3c05370e1c2cf819e6156991c762b2247e8a5b51edb852bb371aca011eccaa581ed577e74d6bf0f2a71e43e7751e3fa6e5f68c2a6e4ccd4fc338fc2a2ea4a9d98018c52fe5953741a53d7f7a6f1c1e57901d64c957dc1776ab0ed28f5754f7d44008ebc5864cfd34dd3b1f1bf82db49674b8e7a3e381882f7cc1035bfdba114280f6c173e337d1813fb47a9b1aaf1d52faac197f90cced9eea754cf441cb262b3117444ad3a265cefb9593d40cdb8a3ae0235cc06baffbcac493bf45852908b014f063c29d85347e808e7ed4be8688327bf3280759ea1ff187287dcabaaee8859a6da782cd2451e2911fe16ca7d","markerColor":"0","edited":"0"}]}
JSONObject jObj = new JSONObject(input);
jArray = jObj.getJSONArray("data");
} catch (JSONException e) {
e.printStackTrace();
}
}
// GSON print of JSON Object from the manually entered "input" variable.
I/System.out: {
"nameValuePairs": {
"data": {
"values": [
{
"nameValuePairs": {
"claimNumber": "f265e5e6513070abd1f711232cfd3a491075f15bc9714cf723e373f02e71a214",
"xlsLine": "8b3490231cd923c133989dd93574de131b6c388a86153a74eb6ae2507193a008c9d3d0264452cc1bd1113d5a722f3ea7975f322461f486be96e789424459e20bcbaf878f5d0efe09426b90c046d881100e166ef0bfcf8721266383aabf3837a213854e8425e92b722791640576d3c0ce7722ff3de2e6005c85df840bea3b10982b7bcf8bec3398ea03e08e6a2879cb29e0e6c3c05370e1c2cf819e6156991c762b2247e8a5b51edb852bb371aca011eccaa581ed577e74d6bf0f2a71e43e7751e3fa6e5f68c2a6e4ccd4fc338fc2a2ea4a9d98018c52fe5953741a53d7f7a6f1c1e57901d64c957dc1776ab0ed28f5754f7d44008ebc5864cfd34dd3b1f1bf82db49674b8e7a3e381882f7cc1035bfdba114280f6c173e337d1813fb47a9b1aaf1d52faac197f90cced9eea754cf441cb262b3117444ad3a265cefb9593d40cdb8a3ae0235cc06baffbcac493bf45852908b014f063c29d85347e808e7ed4be8688327bf3280759ea1ff187287dcabaaee8859a6da782cd2451e2911fe16ca7d",
"markerColor": "0",
"edited": "0"
}
}
]
}
}
}
Have tried php output with and without slashes. No change... still malformed.
Have tried stripping non-standard chars. There are none.
Have forced charset "UTF-8". No difference.
Have searched and tried every conceivable solution for this on Google. Nothing works.
I'm at a loss as to what to try next. Totally confused on why Android can't use the returned Json string,
but can use it if you manually take the same string and put it in a variable in the code directly.
Can someone tell me if this is a known bug, if the JSON really is malformed or if something else comes to mind?
Thank you
EDIT
Here is the PHP that creates the json to return to Android.
$options = array( "Scrollable" => SQLSRV_CURSOR_KEYSET );
$stmt2 = sqlsrv_query( $conn3, $tsql1, $params, $options);
$row_count = sqlsrv_num_rows($stmt2);
if ($row_count === false) {
echo("failed");
} else {
while( $userClaims = sqlsrv_fetch_array($stmt2, SQLSRV_FETCH_ASSOC) ) {
$claimNum = $userClaims['ClaimNumber'];
$xls = $userClaims['XLS'];
$color = $userClaims['Color'];
$edited = "0";
$keyvals = (object) array("claimNumber" => $claimNum, "xlsLine" => $xls, "markerColor" => $color, "edited" => $edited);
array_push($response,$keyvals);
}
$encoded = json_encode(array('data' => $response));
EDIT 2
The following is the complete php section of code that creates the json return string. The array is initialized at the top. Have written the php json string to a text file on server and copied the text to a json checker and it works fine.
$response = array();
$i = 0;
$param1 = $token;
$params = array( &$param1);
$tsql1 = "SELECT * FROM Claims WHERE Token = ? AND DeletionFlag = 0";
$options = array( "Scrollable" => SQLSRV_CURSOR_KEYSET );
$stmt2 = sqlsrv_query( $conn3, $tsql1, $params, $options);
$row_count = sqlsrv_num_rows($stmt2);
if ($row_count === false) {
echo("failed");
} else {
while( $userClaims = sqlsrv_fetch_array($stmt2, SQLSRV_FETCH_ASSOC) ) {
$claimNum = $userClaims['ClaimNumber'];
$xls = $userClaims['XLS'];
$color = $userClaims['Color'];
$edited = "0";
$keyvals = (object) array("claimNumber" => $claimNum, "xlsLine" => $xls, "markerColor" => $color, "edited" => $edited);
array_push($response,$keyvals);
}
$encoded = json_encode(array('data' => $response));
echo $encoded;
}
sqlsrv_close($conn3);
Thank you for your help Andy. I finally figured it out. I found a line of code in the php file that was out of place. It was trying to json_decode an empty string. This is what was generating the extra 36 chars about the malformed string in my actual response. Once I moved it to the correct place, everything started working beautifully. Should have known better, most likely a blasted copy/paste error. Should teach me not to be lazy and actually type ALL my code. Thanks, again!!

HttpURLConnection is returning garbage from a .php file

I have been trying to get JSON data from a .php file. which is returning garbage value. But if I put the url in browser it is showing me the json data perfectly. Here is the code snippet
String authString = username + ":" + password;
byte[] authEncBytes = Base64.encode(authString.getBytes(),0);
String authStringEnc = new String(authEncBytes);
URL url = new URL(urlString);
HttpURLConnection httpConn = (HttpURLConnection) url.openConnection();
httpConn.setAllowUserInteraction(false);
httpConn.setInstanceFollowRedirects(true);
httpConn.setRequestProperty("Content-type", "application/json");
httpConn.setRequestProperty("Authorization", "Basic " + authStringEnc);
httpConn.setRequestMethod("GET");
httpConn.connect();
InputStream stream = httpConn.getInputStream();
And for converting it from input stream to string
public static String convertinputStreamToString(InputStream ists)
throws IOException {
if (ists != null) {
StringBuilder sb = new StringBuilder();
String line;
try {
BufferedReader r1 = new BufferedReader(new InputStreamReader(
ists, "UTF-8"));
while ((line = r1.readLine()) != null) {
sb.append(line).append("\n");
}
} finally {
ists.close();
}
return sb.toString();
} else {
return "";
}
}
PROIBLEM is this if I bring "sb" it returns weird garbage value. seems like js code like the following
function toNumbers(d){var e=[];d.replace(/(..)/g,function(d){e.push(parseInt(d,16))});return e}function toHex(){for(var d=[],d=1==arguments.length&&arguments[0].constructor==Array?arguments[0]:arguments,e="",f=0;fd[f]?"0":"")+d[f].toString(16);return e.toLowerCase()}var a=toNumbers("f655ba9d09a112d4968c63579db590b4"),b=toNumbers("98344c2eee86c3994890592585b49f80"),c=toNumbers("72355c05897edf080a57d7f54b23a51e");document.cookie="__test="+toHex(slowAES.decrypt(c,2,a,b))+"; expires=Thu, 31-Dec-37 23:55:55 GMT; path=/"; document.cookie="referrer="+escape(document.referrer); location.href="http://emgcall.byethost9.com/getData.php?ckattempt=1";This site requires Javascript to work, please enable Javascript in your browser or use a browser with Javascript support
I have tried set content to Application/Json in my php file. same result.
What is the problem and solution might be.
Here is the php code
<?php
header('Content-type: application/json');
function x(){
$con=mysqli_connect("com","","","");
if (mysqli_connect_errno($con)){
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$sql = "SELECT * FROM emgCall";
$result = mysqli_query($con,$sql);
if (mysqli_num_rows($result) > 0) {
$response["numbers"] = array();
while($row = mysqli_fetch_assoc($result)){
$number = array();
$number['id']=$row['id'];
$number['number']=$row['number'];
$number['image']=base64_encode($row['image']);
array_push($response["numbers"], $number);
}
$son=json_encode($response);
mysqli_close($con);
return $son;
} else {
$outputs["success"] = 0;
$outputs["message"] = "No products found";
}
}
echo $data = x();
?>
At first you need to check where from these html response coming from.
I already checked it and for each request it return an html response which contains a redirect url. It's working on browser, because browser automatically render this html response and then redirect to the url.
You can also check it by yourself: goto this site: http://requestmaker.com/ and place this url : http://emgcall.byethost9.com/getData.php?ckattempt=1 and make a get request. You can then observe the actual response from your code.
So, please check if there is any module or service added to php server that automatically added some cookies/auth-data and then force browser to redirect.
I'm assuming that your url is : http://emgcall.byethost9.com/getData.php?ckattempt=1
Thanks.

Android Data Parsing with php

I am fetching data from a php server in its normal format..the columns are details and image..
I want the image in base64 format nd the details in utf8 format..all this data into one array that will be json encoded and will then be parsed at android side..How do i do this..so that i can Json parse in this manner..
String result= convertStreamToString(is);
JSONObject json=new JSONObject(result);
jArray=json.getJSONArray("details");
for(int i=0;i<jArray.length();i++)
{
JSONObject c=jArray.getJSONObject(i);
String detail=c.getString("details");
String image=c.getString("image");
Log.v("topics", topic);
is.close();
}
The php code:
while($out=mysql_fetch_assoc($result))
{
echo $out;
print_r(base64_encode($out[image]));
echo base64_encode($out['image']);
echo utf8_encode($out['details']);
$tempImage = base64_encode($out['image']);
echo $tempImage;
$tempDetails = utf8_encode($out['details']);
$post[] = array("image"=>$tempImage);
$post []= array("details"=>$tempDetails);
}
echo json_encode(array("login"=>$post));
i think that you can use this link to learn about this
Issues-parsing data to the php and jsons
or visit this : http://androidexample.com/JSON_Parsing_-_Android_Example/index.php?view=article_discription&aid=71&aaid=95

Getting response in android from PHP

I am getting response from php to android, see below .php
<?php
$username = $_POST[username];
$password = $_POST[password];
if($username == "himm")
{
if($password == "rangde"){
echo "success" ;
}
else{
echo "passwor is wrong.";
}
}
else
{
echo "fail";
}
?>
i am getting success in logcat window of android. But here in android i have made comparison like below,
BufferedReader reader = new BufferedReader(new InputStreamReader(is,"iso-8859-1"),8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
is.close();
result = sb.toString();
Log.v("","Result : "+result);
Log.v("","this is Result: "+result.equalsIgnoreCase("success"));
if(result.equals("success")){
Log.v("","Login successfully......");
}
else{
Log.v("","Fail to login......");
}
but in logcat window i see "fail to login" message. Php send response as "success" but which type ?
Here condition of if(result.equals("success")) should be true. Please any body give me idea or suggestions to achieve thies..........thank you in advance
sb.append(line + "\n"); modifies the 'success' to 'success\n' so the if(result.equals("success")){ fails because 'success\n' does not match 'success'.
In your android code, you add a trailing LineFeed to the result you receive from php :
sb.append(line + "\n");
So you actually compare 'success' to 'success\n' which is false.
In addition to previously posted answer (which are correct), I would like to point out that HTTP contains mechanisms to do what you are trying to do.
Http authentication allows you to use standard Http return codes (200 in case of success, 401 in case of authentication failure) and to use existing systems to handle that part (most frameworks will provide such).
It also allows you to separate authentication from the rest of the message you send back from the server, and to compare the authentication status at soon as you receive the headers from the server.

JSON exception in Android

I am trying to execute query on database in the localhost and send the JSON object to the client in android. I m not been able to know what is the problem in my code. So some one please help me on this regard.
My php code is the one where i m sending the JSON object.
php code
query executed successfully..
$row=mysql_fetch_array($result1);
$email=$row['EM'];
$pass=$row['PASS'];
$post=array("email"=>$email, "pass"=>$pass);
$posts[] = array("post"=>$post);
//echo "SUCCESS";
header('Content-type: application/json');
echo json_encode(array("posts"=>$posts));
And in android side i ve this code below;
HttpResponse response = doPost(url, kvPairs);
String responseBody=response.toString();
String temp = EntityUtils.toString(response.getEntity());
if (temp.compareTo("SUCCESS")==0)
{
Toast.makeText(this, "Working", Toast.LENGTH_LONG).show();
}
Above part executes ..
Below code throws a JSON exception
JSONObject json = new JSONObject(responseBody);
JSONArray jArray = json.getJSONArray("posts");
no_of_obj=jArray.length();
nemail=new String[no_of_obj];
npass=new String[no_of_obj];
for (int i = 0; i < jArray.length(); i++) {
JSONObject e = jArray.getJSONObject(i);
String s = e.getString("post");
JSONObject jObject = new JSONObject(s);
Toast.makeText(context,jObject.getString("email")+":"+jObject.getString("pass") , duration).show();
nemail[i]=jObject.getString("email");
npass[i]=jObject.getString("pass");
}
In the log cat i can see : The json string must begin with "{"....
Probably you cannot do this
String s = e.getString("post");
because there is no "post" key in the array of Strings you have given,...
Try doing this,
String s = e.has("post")?e.getString("post"):null;
and then on next line keep a null check before Creating JSONObject..
Try this
$posts['data'] = $post;
//echo "SUCCESS";
header('Content-type: application/json');
echo json_encode($posts);

Categories