deleting a row in mysql and android - relational databases - php

In android app the user can insert a player's name, his rating and post that data in my server. This is done by the following working code.
<?php
session_start();
require "init.php";
header('Content-type: application/json');
error_reporting(E_ALL);
ini_set("display_errors", 1);
$id_isSet = isset($_POST['player_id']);
$user_id_isSet = isset($_POST['User_Id']);
$best_player_isSet = isset($_POST['player']);
$rate_isSet = isset($_POST['rating']);
if($id_isSet && $user_id_isSet && $best_player_isSet && $rate_isSet){
$id = $_POST["player_id"];
$user_id = $_POST['User_Id'];
$best_player = $_POST['player'];
$rate = $_POST['rating'];
$sql_query = "INSERT INTO rating_players_table VALUES('$id','$best_player','$rate','$user_id');";
if(mysqli_query($con,$sql_query)){
$don = array('result' =>'success','message'=>'Προστέθηκε');
//$don = array('result' =>"success","message"=>"$id");
}
}else if(!$best_player_isSet){
$don = array('result' =>"fail","message"=>"Insert player name");
}else if(!$rate_isSet){
$don = array('result' =>"fail","message"=>"Rate player");
}
echo json_encode($don);
?>
Now I want the user to delete the players he rated. So for that I am doing the following.
<?php
include("init.php");
$delete_post = "delete from rating_players_table where
id='$_GET['player_id']'";
$run_delete = mysqli_query($con,$delete_post);
echo json_encode($don);
}
?>
Do you see what I am doing in the deleting code? I use the $_GET['player_id'] is order to delete the corresponding row. However, this code doesn't work. Any ideas on this problem? I am suspecting that the $_GET['player_id'] returns nothing, even if the rating_players_table has some rows of data.
Finally this is my android code.
public void deleteRatedPlayer() {
JsonObjectRequest jsonObjReq = new JsonObjectRequest(Request.Method.GET,
URL.DELETE_RATED_PLAYER,
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
Log.d("TAG", response.toString());
try {
if (response.getString("result").equals("success")) {
Toast.makeText(getApplicationContext(), response.getString("message"), Toast.LENGTH_LONG).show();
} else if (response.getString("result").equals("fail")) {
Toast.makeText(getApplicationContext(), response.getString("message"), Toast.LENGTH_LONG).show();
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
});
// Adding request to request queue
AppController.getInstance().addToRequestQueue(jsonObjReq);
}
#Override
public boolean onKeyDown(int keyCode, KeyEvent event)
{
return (keyCode == KeyEvent.KEYCODE_BACK ? true :
super.onKeyDown(keyCode, event));
}
}

First of all, to fix your problem fix the deletion line:
// you cannot include $_GET['player_id'] directly in your string
// between the double quotes, you need to use concatenation in this case
$delete_post = "delete from rating_players_table where id='" . $_GET['player_id'] . "'";
Although this should solve the syntax problem, you still have another one: you don't check the input. I suggest you read about prepared statements in mysqli, about filter_input and SQL injection. Each one of the topics can be easily found with simple search.
// filter_input example usage
$player_id = filter_input(INPUT_GET, 'player_id', FILTER_SANITIZE_FULL_SPECIAL_CHARS);
$delete_post = "delete from rating_players_table where id='$player_id'";
Also, I suggest you add some kind of an authorization to limit users' ability to remove another users' entries. Currently, if a player sends a request, you delete the row directly, but what if the user sends you another one's id?

Related

Android/php: Using PDO to retrieve a set of results using 'LIKE', and parse to JSON

I'm trying to use a query to search a database, and return a few columns from a table wherever the user's name is LIKE the search query. I.e if I type in 'M', names like Max, Matthew etc. would be retrieved. However, when executed the query isn't returning anything. I've surrounded it all with try/catch functions and they work properly, echoing an integer that I can use, but I'd much prefer that the code actually did what it's meant to do. I've spent quite a while fiddling with this, first trying to use MySqli then moving to PDO since everyone online thinks it's better.
If anyone can see what's wrong with this, please don't hesitate to correct it!
The server-side script is below:
if(!empty($_POST['name'])){
$host =
$db =
$user =
$password =
$charset =
$dsn = 'mysql:host=localhost;dbname=dbname';
$opt = [
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
PDO::ATTR_EMULATE_PREPARES => false,
];
$pdo = new PDO($dsn,$user,$password,$opt);
$response = array();
$name = $_POST['name'];
$query = "SELECT user_id, name, email FROM users WHERE name LIKE ?";
try {
$stmt = $pdo->prepare("SELECT user_id, name, email FROM users WHERE name LIKE ?");
$stmt->execute([$name]);
$result = $stmt->fetch();
} catch (Exception $e) {
echo "99"; //Statement failed
}
if ($result !== false) {
foreach($result as $row) {
echo json_encode($row['user_id']);
echo json_encode($row['name']);
echo json_encode($row['email']);
}
} else {
echo '2'; //Empty result
}
$dsn = null;
} else {
echo "3"; //No search entry
}
The relevant code from AndroidStudio is as follows:
#Override
public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
final String name = searchInput.getText().toString();
Response.Listener<String> responseListener = new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
System.out.println(response);
System.out.println(name);
if(response != null) {
System.out.println("Statement executed");
} else if (Integer.parseInt(response) == 2) {
System.out.println("Statement executed, but result invalid");
Toast.makeText(getApplicationContext(), "No results found", Toast.LENGTH_SHORT).show();
} else if (Integer.parseInt(response) == 3) {
System.out.println("Search field empty");
Toast.makeText(getApplicationContext(), "No search entry", Toast.LENGTH_SHORT).show();
} else if (Integer.parseInt(response) == 99) {
System.out.println("Failed to execute");
Toast.makeText(getApplicationContext(), "Statement failure", Toast.LENGTH_SHORT).show();
} else {
JSONArray jsonResponse = new JSONArray(response);
}
} catch (JSONException e) {
e.printStackTrace();
}
}
};
PopupContactRequest AddContactRequest = new PopupContactRequest(name, responseListener);
RequestQueue queue = Volley.newRequestQueue(PopupAddContact.this);
queue.add(AddContactRequest);
}
Once I can actually get some useful data passed to the app, I'd like to populate a search-suggestion type listview with it, so that the user can select the appropriate person to add. If anyone also knows how to do this, feel free to add it as a comment or message me, as I need all the help I can get with this!
Cheers,
J
You want data which match beginning of string so in like you have to append % at end
try {
$stmt = $pdo->prepare("SELECT user_id, name, email FROM users WHERE name LIKE ?");
$name = $name."%"; // add this line
$stmt->execute([$name]);
$result = $stmt->fetch();
} catch (Exception $e) {
echo "99"; //Statement failed
}
To have a functional LIKE Statement you need to be aware, that you need to add a precent sign as a wildcard in mysql.
This will get Names startig with "M"
SELECT user_id, name, email FROM users WHERE name LIKE 'M%'
This will get names ending with "M"
SELECT user_id, name, email FROM users WHERE name LIKE '%M'
This will get names that contain "M" at some place
SELECT user_id, name, email FROM users WHERE name LIKE '%M%'

unable to get proper reply from PHP to android

I am creating an app for which I have to maintain a table(login registration), for connecting my android app to the table I am using PHP.
Android code
try {
JSONObject jsonResponse = new JSONObject(response);
boolean success = jsonResponse.getBoolean("success");
if (success) {
Intent intent = new Intent(RegisterActivity.this, Login.class);
RegisterActivity.this.startActivity(intent);
} else if(!success)
{ JSONObject jsonResponse2 = new JSONObject(response);
String errval = new String();
errval=jsonResponse2.getString("errval");
AlertDialog.Builder builder = new AlertDialog.Builder(RegisterActivity.this);
builder.setMessage(errval)
.setNegativeButton("retry", null)
.create()
.show();
}
} catch (JSONException e) {
e.printStackTrace();
Toast.makeText(getApplicationContext(), "Error submitting registration", Toast.LENGTH_SHORT).show();
}
PHP code:-
require 'config.php';
$file = 'outfile.txt';
if ($_POST) {
file_put_contents($file,"~~~~~~~~~~~~~~~~~~~~\n");
foreach ($_POST as $KEY => $VAL) {
file_put_contents($file,$KEY."=>".$VAL."\n", FILE_APPEND);
}
if (#$_POST["Email_id"] and #$_POST["hash"]) {
$email = strtolower($_POST["Email_id"]);
$username = strtolower($_POST["Username"]);
$hash = $_POST["hash"];
$echk = $my->Execute("select count(*) from users where email = '$email'");
if ($echk->fields[0] == 0) {
$uchk = $my->Execute("select count(*) from users where user = '$username'");
if ($uchk->fields[0] == 0) {
$ins = $my->Execute("insert into users values (default,'$username','$email','$hash',default)");
$error["success"] = true;
$error["errval"] = "success";
file_put_contents($file,"success", FILE_APPEND);
} else {
$error["success"] = false;
$error["errval"] = "User: $username already exists";
}
} else {
$error["success"] = false;
$error["errval"] = "Email: $email already exists";
}
} else {
$error["errval"] = "Missing a key: 'Email_id' or 'hash'";
}
file_put_contents($file,"~~~~~~~~~~~~~~~~~~~~\n", FILE_APPEND);
$json = json_encode($error);
print_r($json);
}
?>
The details are being entered in the DB without any issues every time, the code also shows if the email is aldready existing in the table, but if the registration is a success, the app throws exception Error submitting registration. cant figure out where the problem is
thank you.
PS. I am new to stackoverflow still learning, forgive if there are any mistakes in post
if (#$echk->fields[0] == 0) {
$uchk = $my->Execute("select count(*) from users where user = '$username'");
if (#$uchk->fields[0] == 0) {
$ins = $my->Execute("insert into users values (default,'$username','$email','$hash',default)");
$error["success"] = true;
$error["errval"] = "success";
file_put_contents($file,"success", FILE_APPEND);
forgot # in if condition

Android Volley. Why is my response always being returned as false?

My PHP file, login.php, looks like this:
<?php
//if($_SERVER['REQUEST_METHOD']=='POST'){
//$username = $_POST['username'];
$username = "Dave";
require_once('dbConnect.php');
$sql = "SELECT * FROM user WHERE username = '$username'";
$result = mysqli_query($con,$sql);
$check = mysqli_fetch_array($result);
if(isset($check)){
echo 'Logged in';
} else {
echo 'Could not log in';
}
//}
?>
When I go to myserver.com/login.php, I see Logged in, because Dave is in my database.
In my Android app, my Volley Log in button looks like this :
private void userLogin() {
username = editTextUsername.getText().toString().trim();
// password = editTextPassword.getText().toString().trim();
StringRequest stringRequest = new StringRequest(Request.Method.POST, LOGIN_URL,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
if(response.trim().equals("Logged in")){
Toast.makeText(LoginActivity.this,"yahoo, you're in",Toast.LENGTH_LONG).show();
openProfile();
}else{
Toast.makeText(LoginActivity.this,"sorry, you're out",Toast.LENGTH_LONG).show();
// Toast.makeText(LoginActivity.this,response,Toast.LENGTH_LONG).show();
}
}
}, etc... etc...
But when I click my Log in button, my toast is always, sorry, you're out. Do you know why ?
Because this:
$check = mysqli_fetch_array($result);
The function returns an array (success) or boolean false (failure). Either way, $check is ALWAYS going to be set, so isset($check) will always return true.
Your logic should be
if ($check === false) {
which means there's no rows (or the query failed).

Getting a response from a php script call

I have an app that sends some information via POST to a php script in a server. It uses Asynchttpclient. How can I also receive a reply back from the server (via json?)? Please help.
This is my php script
if($_POST["mode"]=="newuser"){
//$gcmRegID = $_GET["shareRegId"];
$gcmRegID = $_POST["regID"];
$gcmUserName = $_POST["userName"];
$gcmFolderName = $_POST["folderName"];
$gcmDate = date("d/m/y");
$conn = new mysqli($servername, $username, $password, $dbname);
if($conn->connect_error){
die("Connection failed: " . $conn->connect_error);
}
$in_user = "user";
$in_password = "NULL";
$in_email = "NULL";
$in_dob = "NULL";
$in_role = "user";
$in_datejoined = "0000-00-00";
$foldername = "NULL";
$sql = "INSERT INTO user(password,regid,name,email,phone,dob,role,datejoined,foldername) VALUES('$in_password','$gcmRegID','$gcmUserName','$in_email','$in_phone','$in_dob','$in_role','$gcmDate','$foldername')";
$substringtitle = substr($gcmRegID,-7);
$combined = $gcmUserName."_".$substringtitle;
if($conn->query($sql)===TRUE){
mkdir("./users/".$gcmFolderName);
$newfoldername = "./users/".$gcmFolderName;
$updatequery = "UPDATE user SET foldername='$newfoldername' WHERE name='$gcmUserName'";
$returnfield = array(
'foldername' => $newfoldername
);
header('Content-type: application/json');
echo json_encode(array('returnfield'=>$returnfield));
if($conn->query($updatequery)===TRUE){
echo "folder updated";
}
//echo "Folder created!";
//}
echo "New record created successfully";
}else{
echo "Error: " . $sql . "<br>" . $conn->error;
}
$conn->close();
echo "Done!";
exit;
}
Android code
//store in the file server (PHP)
private void storeREG(final String registerID,String userName,String folderName){
pg.show();
params.put("regID", registerID);
params.put("userName",userName);
params.put("folderName", folderName);
params.put("mode","newuser");
Log.d("STORE","STORE");
//Make RESTful webservice call
AsyncHttpClient client = new AsyncHttpClient();
client.post(AppConstants.SERVER_URL, params, new AsyncHttpResponseHandler() {
#Override
public void onSuccess(String content) {
pg.hide();
if (pg != null) {
pg.dismiss();
}
Toast.makeText(applicationCtx, "ID sharing successful", Toast.LENGTH_LONG).show();
Intent home = new Intent(applicationCtx, HomeActivity.class);
home.putExtra("regID", registerID);
Log.d("REGID", registerID);
startActivity(home);
finish();
}
#Override
public void onFailure(int statusCode, Throwable error, String content) {
pg.hide();
if (pg != null) {
pg.dismiss();
}
Log.d("ERRORTHROW", error.toString());
if (statusCode == 404) {
Toast.makeText(applicationCtx, "Requested resource not found", Toast.LENGTH_LONG).show();
} else if (statusCode == 500) {
Toast.makeText(applicationCtx, "Something went wrong at the server", Toast.LENGTH_LONG).show();
} else {
Log.d("SHOWME", String.valueOf(statusCode));
Toast.makeText(applicationCtx, "Unexpected error occurred", Toast.LENGTH_LONG).show();
}
}
});
}
Hopefully I can get help with this.
You may try to revise your PHP Code. Below is a well-commented sample code to get you started:
<?php
// EXPLICITLY INSTRUCT THE HEADER ABOUT THE CONTENT TYPE. HERE - JSON
header('Content-type: application/json');
if($_POST["mode"]=="newuser"){
$gcmRegID = htmlspecialchars(trim($_POST["regID"]));
$gcmUserName = htmlspecialchars(trim($_POST["userName"]));
$gcmFolderName = htmlspecialchars(trim($_POST["folderName"]));
$gcmDate = date("d/m/y");
// I WOULD STRONGLY SUGGEST YOU USE PDO FOR YOUR DATABASE TRANSACTIONS:
// HERE'S HOW:
//DATABASE CONNECTION CONFIGURATION:
defined("HOST") or define("HOST", "localhost"); //REPLACE WITH YOUR DB-HOST
defined("DBASE") or define("DBASE", "database"); //REPLACE WITH YOUR DB NAME
defined("USER") or define("USER", "root"); //REPLACE WITH YOUR DB-USER
defined("PASS") or define("PASS", "root"); //REPLACE WITH YOUR DB-PASS
// ESTABLISH A CONNECTION AND DO YOUR WORK WITHIN A TRY-CATCH BLOCK...
try {
$dbh = new PDO('mysql:host='.HOST.';dbname='. DBASE,USER,PASS);
$dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
// HERE: ALL YOUR BUSINESS LOGIC...
$in_user = "user";
$in_password = "NULL";
$in_email = "NULL";
$in_phone = "NULL";
$in_dob = "NULL";
$in_role = "user";
$in_dateJoined = "0000-00-00";
$folderName = "NULL";
$insertSQL = "INSERT INTO user(`password`, `regid`, `name`, `email`, `phone`, `dob`, `role`, `datejoined`, `foldername`) ";
$insertSQL .= " VALUES(:inPassword, :gcmRegID, :gcmUserName, :inEmail, :inPhone, :inDOB, :inRole, :gcmDate, :folderName)";
$arrInsertData = array(
'inPassword' => $in_password,
'gcmRegID' => $gcmRegID,
'gcmUserName' => $gcmUserName,
'inEmail' => $in_email,
'inPhone' => $in_phone,
'inDOB' => $in_dob,
'inRole' => $in_role,
'gcmDate' => $gcmDate,
'folderName' => $folderName
);
// PREPARE THE INSERT QUERY:
$insertStmt = $dbh->prepare($insertSQL);
// INSERT THE NEW ROW:
$insertStmt->execute($arrInsertData);
// OBTAIN THE ID OF THE INSERTED ROW TO BE USED AS SUFFIX FOR YOUR USER FOLDER
$id = $dbh->lastInsertId();
// WHAT HAPPENS WHEN 2 USERS HAVE THE SAME USERNAME??? DID YOU THINK ABOUT THAT?
// TO CIRCUMVENT THIS ISSUE; I WOULD SUGGEST FIRST TO INSERT THE DATA TO THE DATABASE...
// THEN USE THE ID AS A SUFFIX TO MAKE EACH USER DIRECTORY UNIQUE & THAT IS THE APPROACH TAKEN HERE THOUGH...
// NOW YOU CAN CREATE YOUR FOLDER USING THIS ID: $id
// LIKE THIS; 2 USERS WITH USERNAME "android_user" CAN HAVE 2 DIFFERENT FOLDERS LIKE SO: "android_user_97" & "android_user_102"
$userDirectory = "./users/" . $gcmFolderName . "_" . $id;
mkdir($userDirectory);
// DID IT OCCUR TO YOU THAT 2 USERS MIGHT HAVE THE SAME USERNAME IN WHICH CASE MYSQL (INSTEAD OF YOU) HAS TO DECIDE WHICH USER TO UPDATE?
// THAT IS WHY DATABASE TABLES ARE DESIGNED TO HAVE UNIQUE IDENTIFIERS LIKE UUID OR ID OR UID OR ANY TOKEN TO MAKE EACH ROW UNIQUE...
// WE ARE ADOPTING THIS APPROACH IN THE UPDATE QUERY... THAT IS: WE UPDATE THE ROW USING THE ID ABOVE... ASSUMING THAT IS A UNIQUE COLUMN THOUGH.
$updateSQL = "UPDATE user SET foldername=:newDirName WHERE id=:ID";
// NOW UPDATE THE ROW TO TAKE INTO ACCOUNT THE UNIQUE USER-DIRECTORY (USING THE ID AS THE KEY)
$arrUpdateData = array(
'newDirName' => $userDirectory,
'ID' => $id // THIS ASSUMES THAT THE PRIMARY KEY OF YOUR TABLE IS CALLED id OTHERWISE USE THE APPROPRIATE KEY NAME: EG: reg_id OR WHATEVER
);
// PREPARE THE UPDATE QUERY:
$insertStmt = $dbh->prepare($updateSQL);
// UPDATE THE NEWLY CREATED ROW:
$insertStmt->execute($arrUpdateData);
// BUILD THE RESPONSE JSON DATA
$arrResponse = array(
'folderName' => $userDirectory,
'id' => $id,
);
// SEND THE RESPONSE AS JSON IF ALL WORKS FINE TILL HERE...
// THAT MEANS: SEND THE DATA IN $arrResponse AND TERMINATE THE SCRIPT - THE JOB IS DONE.
// NO NEED FOR ALL THOSE ECHO STATEMENTS AS THE YOU ARE EXPLICITLY SENDING BACK JSON DATA.
die( json_encode($arrResponse) );
}catch(PDOException $e){
// IF THERE WAS ANY KIND OF PDO ERROR, SEND IT BACK ANYWAYS - BUT ALSO AS JSON:
$arrResponse = array(
'error' => $e->getMessage()
);
die( json_encode($arrResponse) );
}
}
I can't test the code right now (sorry), but I think it should be something like this:
try {
RequestParams rParams = new RequestParams();
rParams.put("example", "example"); // POST
AsyncHttpClient client = new AsyncHttpClient();
client.get(pageURL, rParams, new JsonHttpResponseHandler() {
#Override
public void onSuccess(JSONArray jsonArray) {
super.onSuccess(jsonArray);
//process JSON Array
}
#Override
public void onFailure(Throwable throwable, JSONArray jsonArray) {
super.onFailure(throwable, jsonArray);
Log.d(TAG, "error", throwable);
}
});
} catch (Exception e) {
Log.d(TAG, "exception", e);
}
Otherwise I made a very light WebClient, you may want to give it a shot:
https://github.com/omaflak/WebClient
This is a short sample:
WebClient client = new WebClient();
client.setOnRequestListener(new OnRequestListener() {
#Override
public void onRequest(String response, int requestID) {
Log.e(TAG, response);
}
#Override
public void onError(int error_code, String message) {
Log.e(TAG, message);
}
});
Pair p = new Pair("field1", "value1");
Pair p2 = new Pair("field2", "value2");
client.requestAsync("http://your-api.com", WebClient.POST, Arrays.asList(p, p2), 1);
// requestAsync(String url, String method, List<Pair<String, String>> postData, int requestID)
To use it, simply add to your dependencies:
compile 'me.aflak.libraries:webclient:1.0'

Fetch user info to sharedpreferences on Login Android

I've created an login activity on android, for that you need email address and password.
It working but since I'm new on android, I don't know how to fetch the rest of user information and save it in the sharedpreferences.
Please help me
login.php
<?php
//load and connect to MySQL database stuff
require("config.inc.php");
if (!empty($_POST)) {
//gets user's info based of a username.
$query = "
SELECT
user_id,
user_name,
user_email,
user_password,
user_salt,
user_mobile,
user_country
FROM users
WHERE
user_email = :email
";
$query_params = array(
':email' => $_POST['user_email']
);
try {
$stmt = $db->prepare($query);
$result = $stmt->execute($query_params);
}
catch (PDOException $ex) {
// For testing, you could use a die and message.
//die("Failed to run query: " . $ex->getMessage());
//or just use this use this one to product JSON data:
$response["success"] = 0;
$response["message"] = "Database Error 1. Please Try Again!";
die(json_encode($response));
}
//This will be the variable to determine whether or not the user's information is correct.
//we initialize it as false.
$validated_info = false;
//fetching all the rows from the query
$row = $stmt->fetch();
if ($row) {
//if we encrypted the password, we would unencrypt it here, but in our case we just
//compare the two passwords
$check_password = hash('sha256', $_POST['user_password'] . $row['user_salt']);
for($round = 0; $round < 65536; $round++)
{
$check_password = hash('sha256', $check_password . $row['user_salt']);
}
if($check_password === $row['user_password'])
{
// If they do, then we flip this to true
$login_ok = true;
}
}
// If the user logged in successfully, then we send them to the private members-only page
// Otherwise, we display a login failed message and show the login form again
if ($login_ok) {
// Here I am preparing to store the $row array into the $_SESSION by
// removing the salt and password values from it. Although $_SESSION is
// stored on the server-side, there is no reason to store sensitive values
// in it unless you have to. Thus, it is best practice to remove these
// sensitive values first.
unset($row['user_password']);
unset($row['user_salt']);
// This stores the user's data into the session at the index 'user'.
// We will check this index on the private members-only page to determine whether
// or not the user is logged in. We can also use it to retrieve
// the user's details.
$_SESSION['user_email'] = $row;
$response["success"] = 1;
$response["message"] = "Login successful!";
die(json_encode($response));
} else {
// Show them their username again so all they have to do is enter a new
// password. The use of htmlentities prevents XSS attacks. You should
// always use htmlentities on user submitted values before displaying them
// to any users (including the user that submitted them). For more information:
// http://en.wikipedia.org/wiki/XSS_attack
$submitted_username = htmlentities($_POST['user_email'], ENT_QUOTES, 'UTF-8');
$response["success"] = 0;
$response["message"] = "Invalid Credentials!";
die(json_encode($response));
}
} else {
?>
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Login</title>
</head>
<body>
<h1>Login</h1>
<form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post">
<p>
<label>Email:</label><br>
<input name="user_email" type="text" value="" maxlength="254"/>
</p>
<p>
<label>Password:</label><br>
<input name="user_password" type="password" value="" maxlength="16"/>
</p>
<p>
<input type="submit" value="Login" name="submit"/>
</p>
</form>
Register
</body>
</html>
<?php } ?>
LoginActivity.java
class AttemptLogin extends AsyncTask<String, String, String> {
/**
* Before starting background thread Show Progress Dialog
*/
boolean failure = false;
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(LoginActivity.this);
pDialog.setMessage(getString(R.string.em_AttemptingLogin));
pDialog.setIndeterminate(false);
pDialog.setCancelable(false);
pDialog.show();
}
#Override
protected String doInBackground(String... args) {
// TODO Auto-generated method stub
// Check for success tag
int success;
/*String user_name = "";*/
String user_email = etEmail.getText().toString();
String user_password = etPassword.getText().toString();
/* String user_mobile = "";
String user_country = "";*/
try {
// Building Parameters
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("user_email", user_email));
params.add(new BasicNameValuePair("user_password", user_password));
Log.d("request!", "starting");
// getting product detail s by making HTTP request
JSONObject json = jsonParser.makeHttpRequest(
LOGIN_URL, "POST", params);
// check your log for json response
Log.d("Login attempt", json.toString());
// json success tag
success = json.getInt(TAG_SUCCESS);
if (success == 1) {
Log.d("Login Successful!", json.toString());
//SAVE
SharedPreferences ui = getSharedPreferences("UserInfo", MODE_PRIVATE);
SharedPreferences.Editor edUi = ui.edit();
/*edUi.putString("user_name", user_name);*/
edUi.putString("user_email", user_email);
/*edUi.putString("user_mobile", user_mobile);
edUi.putString("user_country", user_country);*/
edUi.commit();
startActivity(new Intent(LoginActivity.this, MainActivity.class));
finish();
// Returns Toast "Login success!"
//return json.getString(TAG_MESSAGE);
} else {
Log.d("Login Failure!", json.getString(TAG_MESSAGE));
return json.getString(TAG_MESSAGE);
}
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
/**
* After completing background task Dismiss the progress dialog
* *
*/
protected void onPostExecute(String file_url) {
// dismiss the dialog once product deleted
pDialog.dismiss();
if (file_url != null) {
Toast.makeText(LoginActivity.this, file_url, Toast.LENGTH_LONG).show();
}
}
}
I've tried the same way that email but don't work, you can see it's commented /* */ on .java
Thanks
Server side
My PHP is rather rusty but I am pretty sure that if you simply echo your json parsed result, then that information is capturen in the JSONObject on your android:
echo json_encode($response);
Cracking up the JSONObject
On your android you should then hopefully have every piece of information from the $result object available.
To pull out that information do something like (unrelated example just to show the mechanics):
JSONObject jsonObject; // ... retreived earlier in the code
try {
if (jsonObject.getString("status").equals("OK")) {
jsonObject = jsonObject.getJSONArray("results")
.getJSONObject(0);
jsonObject = jsonObject.getJSONObject("geometry");
jsonObject = jsonObject.getJSONObject("location");
String lat = jsonObject.getString("lat");
String lng = jsonObject.getString("lng");
position = new LatLng(Double.valueOf(lat),
Double.valueOf(lng));
}
} catch (JSONException e) {
Log.e(TAG, e.getMessage(), e);
}
Suggestion regarding shared preferences
Example saving string in shared preferences and retrieve it again anywhere in your app.
public class PreferencesData {
public static void saveString(Context context, String key, String value) {
SharedPreferences sharedPrefs = PreferenceManager
.getDefaultSharedPreferences(context);
sharedPrefs.edit().putString(key, value).commit();
}
public static String getString(Context context, String key, String defaultValue) {
SharedPreferences sharedPrefs = PreferenceManager
.getDefaultSharedPreferences(context);
return sharedPrefs.getString(key, defaultValue);
}
}
Usage:
// save a note to the 'mynote' key
PreferencesData.saveString(context, "mynote", "This is a test note");
// retrieve the 'This is a test note' String
String note = PreferencesData.getString(context, "mynote", "");
Optional note:
I prefer to have as few hard coded strings as possible, so I have a /res/values/strings_prefkeys.xml file that I use to store preference keys. For the note example this file would contain:
<?xml version="1.0" encoding="utf-8"?>
<resources>
<string name="key_note">key_note</string>
</resources>
And the above save and retrieval would then become:
// save a note to the 'mynote' key
PreferencesData.saveString(context, context.getString(R.string.key_note), "This is a test note");
// retrieve the 'This is a test note' String
String note = PreferencesData.getString(context, context.getString(R.string.key_note), "");
This is simply a matter of organisation and minimizing the risk of accidental duplicate keys that would yield some hard to track down bugs.
I've managed to fetch user information with this easy way after a long time of tweaking:
Login.php
$query = "SELECT * FROM users WHERE user_email = :email";
and
$response["success"] = 1;
$response["message"] = "Sessão iniciada com sucesso!";
$response["user_name"] = $row['user_name'];
$response["user_mobile"] = $row['user_mobile'];
$response["user_country"] = $row['user_country'];
// echoing JSON response
echo json_encode($response);
//die(json_encode($response));
on LoginActivity.java doInBackground
String user_name = "";
String user_email = etEmail.getText().toString();
String user_password = etPassword.getText().toString();
String user_mobile = "";
String user_country = "";
if success
user_name = json.getString("user_name");
user_mobile = json.getString("user_mobile");
user_country = json.getString("user_country");
//SAVE
SharedPreferences ui = getSharedPreferences("UserInfo", MODE_PRIVATE);
SharedPreferences.Editor edUi = ui.edit();
edUi.putString("user_name", user_name);
edUi.putString("user_email", user_email);
edUi.putString("user_mobile", user_mobile);
edUi.putString("user_country", user_country);
edUi.commit();
This was the "easy" way I've found, I know it's not the best but it works just fine! :)

Categories