0

I am trying create a login and registration in my android app but the problem I am facing is like, I am able to do my registration in the table but I am not able to login with those registered values. It is showing me 'failure' message of my login php script. Below is my "login.php" file

 <?php
     if($_SERVER['REQUEST_METHOD']=='POST'){
     $username = $_POST['username'];
     $password = $_POST['password'];
     require_once('dbConnect.php');
     $sql = "SELECT * FROM register WHERE username = '$username' AND  password='$password'";
     $result = mysqli_query($con,$sql);
     $check = mysqli_fetch_array($result);
     if(isset($check){
    echo'sucess'
    }else{
    echo'failure'
    }
    }
    ?>

And this is my android Java File 'Login.java'

package com.example.tejask.add4u;
import android.app.ProgressDialog;
        import android.content.Context;
        import android.content.Intent;
        import android.content.SharedPreferences;
        import android.os.AsyncTask;
        import android.os.Bundle;
        import android.support.annotation.Nullable;
        import android.support.v7.app.AppCompatActivity;
        import android.view.View;
        import android.widget.Button;
        import android.widget.EditText;
        import android.widget.TextView;
        import android.widget.Toast;
        import com.android.volley.AuthFailureError;
        import com.android.volley.DefaultRetryPolicy;
        import com.android.volley.Request;
        import com.android.volley.RequestQueue;
        import com.android.volley.Response;
        import com.android.volley.VolleyError;
        import com.android.volley.toolbox.StringRequest;
        import com.android.volley.toolbox.Volley;
        import java.util.HashMap;
        import java.util.Map;

/**
 * Created by tejas k on 26-04-2016.
 */


       public class Login extends AppCompatActivity implements View.OnClickListener {
        private Button btnLogin;
        private TextView txtRegister;
        private EditText editUsername,editPassword;
        public static final String USER_NAME = "username";
        public static final String KEY_PASSWORD="password";

        private static final String LOGIN_URL = "http://10.0.2.2/loginn.php";

        private String username;
        private String password;

        @Override
        protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.login);

        editUsername = (EditText) findViewById(R.id.editUsername);
        editPassword = (EditText) findViewById(R.id.editPassword);
        btnLogin= (Button) findViewById(R.id.btnLogin);
        txtRegister=(TextView)findViewById(R.id.txtRegister);
        txtRegister.setOnClickListener(this);
        btnLogin.setOnClickListener(this);
        }
        private void userLogin() {
        username = editUsername.getText().toString().trim();
        password = editPassword.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("success")){
        openProfile();
        }
        else{                     Toast.makeText(Login.this,response,Toast.LENGTH_LONG).show();
        }
        }
        },new Response.ErrorListener() {
        @Override
        public void onErrorResponse(VolleyError error) {
                           Toast.makeText(Login.this,error.toString(),Toast.LENGTH_LONG ).show();
        }
        }){
        @Override
        protected Map<String, String> getParams() throws AuthFailureError {
        Map<String,String> map = new HashMap<String,String>();
        map.put(USER_NAME,username);
        map.put(KEY_PASSWORD,password);
        return map;
        }
        };
        RequestQueue requestQueue = Volley.newRequestQueue(this);
        requestQueue.add(stringRequest);
        }

        private void openProfile(){
        Intent intent = new Intent(this,ProfileActivity.class);
        intent.putExtra(USER_NAME, username);
        startActivity(intent);
        }

        @Override
        public void onClick(View v) {
        switch (v.getId()){
        case R.id.btnLogin:
        userLogin();
        break;

        case R.id.txtRegister:
        Intent register = new Intent(Login.this,Register.class);
        startActivity(register);
        break;
        }
        }
        }
klaus19
  • 23
  • 1
  • 10
  • Missing ) on `if(isset($check){` is this a typo? – Matt May 10 '16 at 10:10
  • `echo` line must end with **`;`** semicolon – Bharatesh May 10 '16 at 10:18
  • **Never store plain text passwords!** Please use PHP's [built-in functions](http://jayblanchard.net/proper_password_hashing_with_PHP.html) to handle password security. If you're using a PHP version less than 5.5 you can use the `password_hash()` [compatibility pack](https://github.com/ircmaxell/password_compat). Make sure that you [don't escape passwords](http://stackoverflow.com/q/36628418/1011527) or use any other cleansing mechanism on them before hashing. Doing so *changes* the password and causes unnecessary additional coding. – Jay Blanchard May 10 '16 at 12:07
  • [Little Bobby](http://bobby-tables.com/) says [your script is at risk for SQL Injection Attacks.](http://stackoverflow.com/questions/60174/how-can-i-prevent-sql-injection-in-php) Learn about [prepared](http://en.wikipedia.org/wiki/Prepared_statement) statements for [MySQLi](http://php.net/manual/en/mysqli.quickstart.prepared-statements.php). Even [escaping the string](http://stackoverflow.com/questions/5741187/sql-injection-that-gets-around-mysql-real-escape-string) is not safe! – Jay Blanchard May 10 '16 at 12:07
  • I am using 5.5 version – klaus19 May 10 '16 at 12:10

1 Answers1

0

In your script you are missing a ) on if(isset($check){.

However I think you should change this into MySQLi prepared statement for security.

You could change your php into the following:

if($_SERVER['REQUEST_METHOD']=='POST'){
    $username = $_POST['username'];
    $password = $_POST['password'];
    require_once('dbConnect.php');
    if($stmt = $con->prepare("SELECT * FROM register WHERE username = ? AND password = ? LIMIT 1")) {
        $stmt->bind_param('ss', $username, $password);
        if (!$stmt->execute()) {
            die('execute() failed: ' . htmlspecialchars($stmt->error));
        }
        $stmt->store_result();
        if ($stmt->num_rows == 1) {
            echo 'success';
        }
        else {
            echo 'failure';
        }
    }
    else {
        die('prepare() failed: ' . htmlspecialchars($con->error));
    }
    $stmt->close();
}

adding LIMIT 1 means you will only get 1 result back or zero if user doesn't exist.

Matt
  • 1,749
  • 2
  • 12
  • 26
  • I tried this one but it is giving a msg like, unexpected ';' at line 6 – klaus19 May 10 '16 at 11:54
  • @Rebecca try now. I missed a ) on the `if($stmt` – Matt May 10 '16 at 11:55
  • Where should I try this? Could you paste the improvised code mate? I'm kind getting confused lil bit. – klaus19 May 10 '16 at 12:09
  • @Rebecca just replace your login.php code with the code I wrote (at least the part from your question replace). Let me know of any errors/results that are occuring. I hope you are not storing passwords as plain text and this is just testing :) – Matt May 10 '16 at 12:38
  • yh..I am storing password as VARCHAR in Mysql Database..:). Is it wrong? I have the snapshot of the error but how to send in comment here? – klaus19 May 11 '16 at 04:13
  • I tried your above code but its still giving me the msg ' failure' mate! – klaus19 May 11 '16 at 04:45
  • I even tried this one http://stackoverflow.com/questions/37154132/login-in-android-using-php-and-mysql. The problem is same one – klaus19 May 11 '16 at 05:58
  • @Rebecca edit your main question with the snap shot. You should encrypt passwords before storing them. If you are still getting failure then are you 100% sure you are using a login that is saved in the database? Same username/password? – Matt May 11 '16 at 06:32
  • @Rebecca echo out the query and paste it directly into the database also – Matt May 11 '16 at 06:34
  • I haven't encrypted the password value in my Database. – klaus19 May 11 '16 at 06:58
  • @Rebecca you should but lets fix this problem first. Have you tried the query directly in the database with the values you are putting into your application? Does this value exist in the database? – Matt May 11 '16 at 07:08
  • Means like, I should put one of the values of username and password directly in the login.php right? I tried still the problem persist.I've put $username = 'ooo' $password = '999' – klaus19 May 11 '16 at 07:21
  • @Rebecca No no, directly into the database. I presume you are using something like phpMyAdmin? Do the SQL query there. – Matt May 11 '16 at 07:28
  • I did checked it now like this SELECT * FROM `register` WHERE username='yes' and password='yes'; and after running it is giving like MySQL returned an empty result set (i.e. zero rows). ( Query took 0.0008 sec ) – klaus19 May 11 '16 at 07:50
  • Hey, I solved the error, there is space in Password column everywhere..:) – klaus19 May 11 '16 at 07:52
  • @Rebecca glad you found the issue :). Did this prepared statement answer work also? – Matt May 11 '16 at 07:56
  • Thank you for your help mate!...Actually I put .trim() after tostring() to remove the space and that was only the issue...And would you mind if I post another query on StackOverflow..sorry and thank you again. P.S You a lot genius. yh it worked, like the one you told me to do right? – klaus19 May 11 '16 at 08:01
  • @Rebecca No worries. Glad it's all working. Is it the question posted 2hrs ago? Will take a look for you – Matt May 11 '16 at 10:57
  • Glad you replied , I thought I offended you by asking help.:) I was saying bout this question http://stackoverflow.com/questions/37157329/registration-in-android-with-php-mysql?noredirect=1#comment61856691_37157329 – klaus19 May 11 '16 at 11:11
  • And Thank you for your login.php file, I forgot to say that.:) – klaus19 May 11 '16 at 11:15