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.
Related
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.
I use json to get a string data from php and i want compare this data whit a string ,even when they are equal but returns false for example
php file:
<?php
echo "ok";
?>
java use 3 log
BufferedReader reader = new BufferedReader(new InputStreamReader(is, "UTF-8"), 8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null)
{
sb.append(line + "\n");
}
is.close();
page_output = sb.toString();
Log.i("page_output", page_output);
Log.i("page_output", String.valueOf(page_output=="ok"));
Log.i("page_output", String.valueOf(page_output.equals("ok")));
log out
07-12 03:42:45.616: I/page_output(2007): ok
07-12 03:42:45.736: I/page_output(2007): false
07-12 03:42:45.736: I/page_output(2007): false
you can see that page_output is ok but returns false
Try this:
Log.i("page_output", String.valueOf(page_output.trim().equals("ok")));
You are appending "\n" at the end of the every line read from your php response. So you're actually comparing "ok\n" with "ok" and that's why the comparison returns false.
The trim() function removes white spaces, including new lines \n.
in this line:
sb.append(line + "\n");
You add the "\n" new line character to your StringBuilder. When you call toString this character will also be put in your String.
Therefore, page_output.equals("ok\n") will be true.
Or you could just delete the '\n' character from the StringBuilder since I do not see any practical usage in your code
I'm using PHP & JSON to extract some data from a database.
This is my PHP file
<?php
error_reporting(0);
ini_set('error_reporting', E_ALL);
ini_set('display_errors','Off');
$mysqli = new mysqli("localhost", "root", $_REQUEST['password'], "");
if ($mysqli->connect_errno) {
echo "Failed to connect to DB.";
die();
} else {
$dbs = array();
$res = $mysqli->query("SHOW DATABASES");
$res->data_seek(0);
if ($res->num_rows > 0) {
while($row = $res->fetch_assoc()) {
$dbs[] = $row;
}
echo json_encode($dbs);
} else {
echo "Failed to get list of databases from server.";
die();
}} ?>
If the password is wrong, then the system outputs "Failed to connect to DB"
In my program, I have things to handle errors, but I am stuck at one part.
let urlString = "http://\(hostTextField.text):\(portTextField.text)/dblist.php? &password=\(passTextField.text)"
let url: NSURL = NSURL(string: urlString)!
let urlSession = NSURLSession.sharedSession()
println(url)
println(urlSession)
//2
let jsonQuery = urlSession.dataTaskWithURL(url, completionHandler: { data, response, error -> Void in
println(response)
println(data)
if (error != nil) {
println("Can't connect using credentials")
dispatch_async(dispatch_get_main_queue(), {
HUDController.sharedController.hide(afterDelay: 0.1)
})
sleep(1)
var refreshAlert = UIAlertController(title: "Camaleon Reports", message: "Can't connect to the database", preferredStyle: UIAlertControllerStyle.Alert)
refreshAlert.addAction(UIAlertAction(title: "Retry", style: .Default, handler: { (action: UIAlertAction!) in
println("Yes Logic")
}))
self.presentViewController(refreshAlert, animated: true, completion: nil)
return }
var err: NSError?
var jsonResult: [Dictionary<String, String>] = NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.MutableContainers, error: &err) as [Dictionary<String, String>]
// 3
if (err != nil) {
println("Still cant connect....")
println("JSON Error \(err!.localizedDescription)")
}
var jsonDB : [Dictionary<String, String>] = jsonResult
for currentDictionary in jsonDB{
var currentEntry = currentDictionary["Database"] as String!
My program crashes if I don't have the right password, but have the right IP address and Port/User for the MYSQL Database.
It crashes with this:
fatal error: unexpectedly found nil while unwrapping an Optional value
and points towards jsonResult. It makes sense, cause I don't retrieve two strings.
My problem is that if my password is off, then my PHP file echoes a string. How can I search for that string so that I can use an if statement and stop my application from crashing?
Your problem is likely in this line (wrapped for clarity):
var jsonResult: [Dictionary<String, String>] =
NSJSONSerialization.JSONObjectWithData(data,
options: NSJSONReadingOptions.MutableContainers,
error: &err) as [Dictionary<String, String>]
When your PHP script reports the error by just returning the string, it has returned invalid JSON. When you use NSJSONSerialization.JSONObjectWithData to parse it, that method will return nil if the JSON is invalid, as yours is.
You then take that value and assign it to a Swift variable that you've declared is not an optional. Trying to assign nil to a variable not declared with either ? or ! is a runtime error in Swift. (You don't get an error at compile time because you're using as to cast the value.)
One way to fix this would be to change your PHP so the error is proper JSON:
echo "{ \"error\": \"Failed to connect to DB.\" }"; # or something, my PHP is rusty
But that still leaves your Swift program in a fragile state; getting anything but proper JSON back from the server will make it crash.
Better is to declare the jsonResult variable as being an optional:
var jsonResult: [Dictionary<String, String>]? =
NSJSONSerialization.JSONObjectWithData(data,
options: NSJSONReadingOptions.MutableContainers,
error: &err) as [Dictionary<String, String>]?
Then in your code you can explicitly check whether jsonResult is nil, and if it is, you know an error has occurred, and can go back and look at the data object to see what it was.
Even that, though, can leave you in trouble. The root of a JSON document doesn't have to be a dictionary; it could be an array. And even if it is a dictionary, the values may not all be strings; they could be numbers, booleans, or nested arrays or dictionaries!
Objective-C's relatively lax type checking makes this easy to deal with, but Swift is stricter. Best might be to use one of the Swift-specific JSON libraries. That'll make your code far more robust.
Good luck!
There are two issues. One is the PHP and one is the Swift.
Your PHP really should never just report an error message. I'd suggest that it always return JSON. This will make it easier for your client code to detect and handle errors appropriately.
<?php
header("Content-Type: application/json");
$response = array();
error_reporting(0);
ini_set('error_reporting', E_ALL);
ini_set('display_errors','Off');
if (!isset($_REQUEST['password'])) {
$response["success"] = false;
$response["error_code"] = 1;
$response["error_message"] = "No password provided";
echo json_encode($response);
exit();
}
$mysqli = new mysqli("localhost", "root", $_REQUEST['password'], "");
if ($mysqli->connect_errno) {
$response["success"] = false;
$response["error_code"] = 2;
$response["mysql_error_code"] = $mysqli->connect_errno;
$response["error_message"] = $mysqli->connect_error;
echo json_encode($response);
exit();
}
if ($res = $mysqli->query("SHOW DATABASES")) {
$dbs = array();
$res->data_seek(0);
if ($res->num_rows > 0) {
while($row = $res->fetch_assoc()) {
$dbs[] = $row;
}
$response["success"] = true;
$response["results"] = $dbs;
} else {
$response["success"] = false;
$response["error_code"] = 3;
$response["error_message"] = "Failed to get list of databases from server.";
}
$res->close();
} else {
$response["success"] = false;
$response["error_code"] = 4;
$response["mysql_error_code"] = $mysqli->errno;
$response["error_message"] = $mysqli->error;
}
$mysqli->close();
echo json_encode($response);
?>
Note, this:
Specifies application/json header for Content-Type;
Always returns a dictionary, containing
a "success" key, which is either true or false;
if an error, an error_code indicating the type of error (1 = no password provided; 2 = connect failed; 3 = no databases found; 4 = some SQL error);
if an error, an error_msg string indicating the error message string; and
if a success, a results array (much like you used to return at the root level).
On the Swift side, you need to :
Change it to look for these various server app-level errors (note, I make the top level structure a dictionary, and your original array of dictionaries a particular value;
You might want to proactively check the statusCode of the response object, to make sure the server gave you a 200 return code (e.g. 404 means that the page was not found, etc.);
You might also want to check for JSON parsing errors (in case some bug in the server prevented well-formed JSON from being returned); and
You really should be percent-escaping the password (because if it included + or & characters, it wouldn't get transmitted successfully otherwise).
Thus, you might have something like:
let encodedPassword = password.stringByAddingPercentEncodingForURLQueryValue()!
let body = "password=\(encodedPassword)"
let request = NSMutableURLRequest(URL: URL!)
request.HTTPBody = body.dataUsingEncoding(NSUTF8StringEncoding)!
request.HTTPMethod = "POST"
let task = NSURLSession.sharedSession().dataTaskWithRequest(request) { data, response, error in
// detect fundamental network error
guard error == nil && data != nil else {
print("network error: \(error)")
return
}
// detect fundamental server errors
if let httpResponse = response as? NSHTTPURLResponse where httpResponse.statusCode != 200 {
// some server error
print("status code was \(httpResponse.statusCode); not 200")
return
}
// detect parsing errors
guard let responseObject = try? NSJSONSerialization.JSONObjectWithData(data!, options: []) as? [String : AnyObject] else {
// some problem parsing the JSON response
print(String(data: data!, encoding: NSUTF8StringEncoding))
return
}
// now parse app-level response to make sure `status` was `true`
guard let success = responseObject!["success"] as? NSNumber else {
print("Problem extracting the `success` value") // we should never get here
return
}
if !success.boolValue {
print("server reported error")
if let errorCode = responseObject!["error_code"] as? NSNumber {
switch (errorCode.integerValue) {
case 1:
print("No password provided")
case 2:
print("Connection failed; probably bad password")
case 3:
print("No databases found")
case 4:
print("Some SQL error")
default:
print("Unknown error code: \(errorCode)") // should never get here
}
}
if let errorMessage = responseObject!["error_message"] as? String {
print(" message=\(errorMessage)")
}
return
}
if let databases = responseObject!["results"] as? [[String : AnyObject]] {
print("databases = \(databases)")
}
}
task.resume()
The percent-escaping code is in a String category:
extension String {
// see RFC 3986
func stringByAddingPercentEncodingForURLQueryValue() -> String? {
let characterSet = NSCharacterSet(charactersInString:"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-._~")
return self.stringByAddingPercentEncodingWithAllowedCharacters(characterSet)
}
}
A couple of other ancillary observations:
Never send a passwords in the clear. Put them in the body of a POST request (not the URL), and then use a https URL.
I'd personally not use the MySQL password part of the app-level authentication. I'd keep MySQL authentication logic encoded on the server-side, and then use your own user authentication table.
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 ;)
I m using Volley library in android to get JsonObject from my server.
i have create the proper json in server with php
but when i get the json from server it occur a weird problem
i m using json_encode in php to produce json
i dont know what are these extra characters in front of json?
do you know how to solve this problem???
this is a error that i got in android
07-18 20:40:49.151: W/System.err(11636): com.android.volley.ParseError: org.json.JSONException: Value ï»? of type java.lang.String cannot be converted to JSONObject
thanks in advance
I would have posted this as a comment but I wanted to post the relevant code that is in the link. If it works, awesome, if not let me know and I will remove this (as I haven't tested it).
From Skip BOM
"The problem is that your UTF-8 string starts with a byte order mark character (BOM) '0xfeff'. We should fix our JSON parsers to skip this character if it exists.
As a workaround, you can use this code to strip the BOM when you go from InputStream to Reader."
public Reader inputStreamToReader(InputStream in) throws IOException {
in.mark(3);
int byte1 = in.read();
int byte2 = in.read();
if (byte1 == 0xFF && byte2 == 0xFE) {
return new InputStreamReader(in, "UTF-16LE");
} else if (byte1 == 0xFF && byte2 == 0xFF) {
return new InputStreamReader(in, "UTF-16BE");
} else {
int byte3 = in.read();
if (byte1 == 0xEF && byte2 == 0xBB && byte3 == 0xBF) {
return new InputStreamReader(in, "UTF-8");
} else {
in.reset();
return new InputStreamReader(in);
}
}
}
"Or you can remove the byte order mark from your file!"