0

I am working on a login/register app. That's my Java Code in my MainActivity:

private void loginUser(){
    pd = ProgressDialog.show(LoginActivity.this, "", "Loading...");
    StringRequest stringRequest = new StringRequest(Request.Method.POST, LOGIN_URL,
            new Response.Listener<String>() {
                @Override
                public void onResponse(String response) {
                    try {
                        JSONObject jsonResponse = new JSONObject(response);
                        System.out.println("JSON RESPONSE: " + jsonResponse.toString());
                        boolean success = jsonResponse.getBoolean("success");
                        if (success) {
                            launchHomeScreen();
                            pd.dismiss();
                            Toast.makeText(LoginActivity.this,"Welcome back " + username,Toast.LENGTH_LONG).show();
                        }
                        else {
                            Toast.makeText(LoginActivity.this,"Wrong Username or Password!",Toast.LENGTH_LONG).show();
                            pd.dismiss();
                        }
                    }
                    catch (JSONException e) {
                        e.printStackTrace();
                        pd.dismiss();
                        Toast.makeText(LoginActivity.this,response,Toast.LENGTH_LONG).show();
                    }
                }
            },
            new Response.ErrorListener() {
                @Override
                public void onErrorResponse(VolleyError error) {
                    pd.dismiss();
                    System.out.println("Error: " + error);
                }
            }){
        @Override
        protected Map<String,String> getParams(){
            Map<String,String> params = new HashMap<>();
            params.put(KEY_USERNAME,username);
            params.put(KEY_PASSWORD,password);
            return params;
        }

    };
    RequestQueue requestQueue = Volley.newRequestQueue(this);
    requestQueue.add(stringRequest);
}
}

login.php:

<?php
$con = mysqli_connect("x", "x", "x", "x");

$username = $_POST["username"];
$password = $_POST["password"];

$statement = mysqli_prepare($con, "SELECT * FROM user WHERE username = ?");
mysqli_stmt_bind_param($statement, "s", $username);
mysqli_stmt_execute($statement);
mysqli_stmt_store_result($statement);
mysqli_stmt_bind_result($statement, $colUserID, $colUsername, $colPassword);

$response = array();
$response["success"] = false;  

while(mysqli_stmt_fetch($statement)){
    if (password_verify($password, $colPassword)) {
        $response["success"] = true;  
    }
}
header('Content-Type: application/json');
echo json_encode($response);
?>

The mysql table looks like: user_id;username;passsword;mobilenumber;email

When i trying to login I get this back in Android logcat, so that error is caused by writting the LOGIN_URL wrong.

E/Volley: [251] BasicNetwork.performRequest: Unexpected response code 404 for http://myserver.xyz/pubic_html/login.php
I/System.out: Error: com.android.volley.ServerError

But there is another Error. I send the right logindatas to the server but everytime I get back success:false.

The weird thing is that I use a similar java code for registration (only with a register.php), and it works, so what is wrong?

This is register.php

<?php
    $connect = mysqli_connect("localhost", "root", "", "user");

    $username = $_POST["username"];
    $password = $_POST["password"];
    $hashedPassword = password_hash($password, PASSWORD_BCRYPT);
    $mobilenumber = $_POST["mobilenumber"];
    $email = $_POST["email"];

    registerUser();
    $response["success"] = false; 
    function registerUser() {
        global $connect, $username, $hashedPassword, $mobilenumber, $email;
        $statement = mysqli_prepare($connect, "INSERT INTO user (username, hashedPassword, mobilenumber, email) VALUES (?, ?, ?, ?)");
        mysqli_stmt_bind_param($statement, "siss", $username, $hashedPassword, $mobilenumber, $email);
        mysqli_stmt_execute($statement);
        mysqli_stmt_close($statement);  
        $response["success"] = true; 
    }
    header('Content-Type: application/json');
    echo json_encode($response);
?>
mc.b
  • 93
  • 1
  • 4
  • 14

1 Answers1

2

404 means the app cannot find the login.php page. Make sure your path to the script is correct.

Try removing the "public_html" from the link. That is your root folder. You do not need to specify this in your link. It should work if you remove that.

EDIT

Since you edited your post after I answered that question, let me edit mine to answer your next. Judging from the password_very function in you php file, you are using password_hash and your password is encrypted with password_hash('yourPass', PASSWORD_BCRYPT);?

In this case, I do not see that you included the library in you PHP script. Just add the following line to your php file and it should work.

include('path/to/password_hash.php');

The problem is, because the file is not found, password_verify is not recognized. I am sure if you change $_POST['username'] and $_POST['password'] to 'YourUsername' and 'YourPassword' and run your file from a browser, you will see all errors, and that will be one of them.

Hope this helps!

EDIT 2

Since you are having issues with the password. In your statement where you insert the password to the database use the password_hash function to hash the password BEFORE you insert it to the database like so:

$hashedPassword = ('Yourpassword', PASSWORD_BCRYPT);

Do your MySQL query and add the $hashedPassword value to the database in the password field. Then retrieve the password and username like you did at the very beginning and use the password_verify function to match the passwords like so:

if (password_verify($_POST['password'], $hashedPassword) {
    // Do your login stuff.
}

Now it should login. (Optional Extra) Also, try looking at PDO to do your sql queries. It is much better. To use PDO do the following:

    //Initiate Connection
        $conn = new PDO('mysql:host='.$db_host.';dbname='.$db_name, $db_user, $db_password);

$stmt = $conn->prepare("SELECT password FROM user WHERE username = :username");

if ($stmt->execute(array(':username' => $_POST['username']))) {
    if ($result = $stmt->fetch(PDO::FETCH_ASSOC)) {
        $passwordFromDb = $result['password']; //This is the password you match in password verify. This password should be hashed in the database. if it is hashed it will look something like this - $2y$07$BCryptRequires22Chrcte/VlQH0piJtjXl.0t1XkA8pw9dMXTpOq.
    }
}

The problem I think is that you have 'Geige' stored as your password in the database and not that hashed string. So when the password_verify function tries to match the passwords, it fails. Your code might be right, but the password in the database might be wrong. When inserting the password to the database, make sure you are hashing it and inserting the hashed password.

I really hope this helps.

EDIT 3 Register Rewrite

<?php
    //Initiate Connection
    $conn = new PDO('mysql:host='.$db_host.';dbname='.$db_name, $db_user, $db_password);

    $username = $_POST["username"];
    $password = $_POST["password"];
    $hashedPassword = password_hash($password, PASSWORD_BCRYPT);
    $mobilenumber = $_POST["mobilenumber"];
    $email = $_POST["email"];

    $stmt = $conn->prepare("INSERT INTO user (username, hashedPassword, mobilenumber, email) VALUES (:username, :password, :mobile, :email)");

    if ($stmt->execute(array(':username' => $username, ':password' => $hashedPassword, ':mobile' => $mobilenumber, ':email' => $email))) {
        $response["success"] = true; 
    } else {
        $response["success"] = false; 
    }

    header('Content-Type: application/json');
    echo json_encode($response);
?>
Christopher Smit
  • 953
  • 11
  • 27
  • Okay. You're right. The Error 404 won't be shown anymore..Thanks man. But there is another Error in the php, because everytime I want loggin I get back: success:false...I use the right logindatas but everytime success: false. – mc.b Apr 09 '17 at 21:43
  • I am assuming you are using password_hash script for your password validation judging from the "password_verify" function. If that is your entire php script that you posted, the error should be that you are not including the password hash script. You need to add the following line to your php script: include('path/to/password_hash.php'); after you do that, if the password in the database is encrypted correctly with the password_hash script, it should return the true parameter. Also try substituting your post variables with hard coded variables and run script from browser to find errors. – Christopher Smit Apr 10 '17 at 04:24
  • I tested with Wamp..What I should rewrite that it will works? – mc.b Apr 19 '17 at 11:24
  • You forgot to add $con infront of your mysqli in your update. Please tell me where you are getting the "password_verify" function – Christopher Smit Apr 19 '17 at 11:28
  • Okay, sorry my fault- I added the $con = ....But what do you mean where you are getting the password_verify function?? That's php manual ..See there http://php.net/manual/de/function.password-verify.php – mc.b Apr 19 '17 at 18:57
  • Okay, and is your password in the database hashed with password_hash function? – Christopher Smit Apr 19 '17 at 19:00
  • I think no...I posted my mysql databse above...Do you see anything wrong? – mc.b Apr 19 '17 at 19:14
  • When you added the value of password to the database you need to add the hashed password.. example: $passwordToDb = password_hash("yourpassword", PASSWORD_BCRYPT); then add $passwordToDb to your database. Because it seems currently you are trying to match an unhashed password with password_verify when it needs to match a hashed password.. so $colPassword should contain a hashed string.. not 'geige'. Hope you understand? – Christopher Smit Apr 19 '17 at 19:18
  • I think I understand .... I updated my php code...But at once I got a new Error...Please have a look at it.. :) And if it's wrong please can you send me a Solution that I understand... :) – mc.b Apr 19 '17 at 19:29
  • Please show me the password in the database.. the physical password string.. I will update my answer now.. – Christopher Smit Apr 19 '17 at 19:32
  • Sorry I am a noob and new at php and mysql – mc.b Apr 19 '17 at 20:03
  • You forgot to write "password_hash" before the "($password, PASSWORD_BCRYPT);" – Christopher Smit Apr 19 '17 at 20:03
  • Try using the PDO example that I gave in my answer and do away with the mysqli. It wil be much better. Also, what is the value of the password in the database? – Christopher Smit Apr 19 '17 at 20:08
  • The value of the password for the user "marcelo.mb" is "geige" – mc.b Apr 19 '17 at 20:12
  • Yes, so I am right... revert all you code back to the way it worked, but returned false. Then just change that value in the database from geige to the hashed password string. It should login then. But I strongly advise in using PDO to do you sql... I even wrote the query to retrieve your pssword. Use it as a guideline. I know it is very advanced if you are new to it, but trust me it will save you a lot of time. – Christopher Smit Apr 19 '17 at 20:14
  • But how I get the hashpasswordvalue of the password "geige"? – mc.b Apr 19 '17 at 20:19
  • echo password_hash('geige', PASSWORD_BCRYPT); – Christopher Smit Apr 19 '17 at 20:20
  • I am really not that familiar with mysqli. Try replacing that entire part where you get the user details with the pdo code I gave in my answer. It does the exact same thing. Except this one wil work without errors. As far as I can tell from the error it is not picking up $statement as a mysqli_stmt.. like a said before.. do away with that code and use PDO.. i gave you the entire piece of code that is the exact same as the code you have there. – Christopher Smit Apr 19 '17 at 20:49
  • Hey I know you answered the Qestio right but do you know what's wrong on the Android java code, because I get following erro: `E/Volley: [150] BasicNetwork.performRequest: Unexpected response code 500 for http://managingserver.xyz/login.php` SO I know there must be something wrong at the java android code... – mc.b Apr 19 '17 at 21:44
  • 500 is a difficult error mainly because the server does not give you the exact reason why it failed. You will need to check the php logs on the server for errors. Does the pho code work online without java code? – Christopher Smit Apr 20 '17 at 04:45
  • When I test myAndroid app with the local wamp server everything works fine, but when i am testing with my real server i get back the error 500 – mc.b Apr 20 '17 at 07:06
  • I really don't know what to do....Because it works fine and the same code on my server don't work...But it is the same code... – mc.b Apr 20 '17 at 07:09
  • Check this answer: http://stackoverflow.com/questions/24136191/unexpected-response-code-500-url-api-android-app/31938219#31938219. Google that specific error code and you will find a lot of answers regarding it. I have not yet encountered an issue like this with Android coding. – Christopher Smit Apr 20 '17 at 07:13
  • Also check this: http://stackoverflow.com/questions/28135008/unexpected-response-code-500-for-post-method – Christopher Smit Apr 20 '17 at 07:16
  • Ok, I will see what the problem is...Can you please rewrite my register.php [in my question edit2:] like you rewrote my login.php ,please? Because this don't work anymore... – mc.b Apr 20 '17 at 08:47