简体   繁体   中英

Android HTTPPOST executing PHP script twice

I'm working on a basic Android APK that is going to be a basic mobile version of a website I run. A portion of the APK enables people to sign up for users accounts (basic registration). I'm using HTTPPOST to send the user form information to a PHP script. All my error checks work (password match, length, etc), but the response I'm getting from a valid submission, I can tell its trying to run the PHP twice. The APK will get an error message and tell the user the user the username and password have been taken, but this is because the php gets run ones, inserts the data, then for some reason runs again and the error catch gets reported instead of just reporting back success the first time it was run. If I take out the error catch to look for duplicate usernames and emails, I can see two inserts in my database. Why is the PHP page getting run twice?

STEPS:

  1. Clear users database.
  2. Insert valid registration information (to not throw errors).

RESULTS

APK gets displayed error message saying username and password have been taken. SQL database shows that the information from the form have been inserted.

FILES

I put logging in my APK and it seems to only call the HTTPPOST once. Below is the JAVA file and PHP page. Any incite on this would be appreciated.

JAVA File

Register.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            Log.d("Registration: ", "Button Pressed");
            dialog = ProgressDialog.show(Register.this, "",
                    "Creating account...", true);
            new Thread(new Runnable() {
                public void run() {
                    new RegisterUser().execute("");
                }
            }).start();
        }
    });
}

private class RegisterUser extends AsyncTask<String, Void, String> {

    @Override
    protected String doInBackground(String... arg0) {
        try {


            httpclient = new DefaultHttpClient();
            // This is the page that will get all the information to create the account
            HTTPPOST = new HttpPost("http://www.linetomyphppage.php");

            NAMEVALUEPAIRS = new ArrayList<NameValuePair>();

            NAMEVALUEPAIRS.add(new BasicNameValuePair("username",username.getText().toString().trim()));  // $Edittext_value = $_POST['Edittext_value'];
            NAMEVALUEPAIRS.add(new BasicNameValuePair("userEmail",emailaddress.getText().toString().trim()));
            NAMEVALUEPAIRS.add(new BasicNameValuePair("password1",password1.getText().toString().trim()));
            NAMEVALUEPAIRS.add(new BasicNameValuePair("password2",password2.getText().toString().trim()));
            NAMEVALUEPAIRS.add(new BasicNameValuePair("newsletter",subscribe));

            HTTPPOST.setEntity(new UrlEncodedFormEntity(NAMEVALUEPAIRS));
            HTTPRESPONSE = httpclient.execute(HTTPPOST);
            ResponseHandler<String> responseHandler = new BasicResponseHandler();
            final String response = httpclient.execute(HTTPPOST, responseHandler);
            Log.d("Registration: ", "Executing Post");
            errorcode = response;

            // Redirect the user depending on the response
            if (response.equalsIgnoreCase("success")) {
               // Toast.makeText(Register.this, "Registration successful", Toast.LENGTH_SHORT).show();
                Log.d("Registration: ", "Registration successful");
                valid = "Successful";
            } else {
                Log.d("Registration: ", "Registration failed");
                valid = "Invalid";
              //  Toast.makeText(Register.this, "Registration failed: " + response, Toast.LENGTH_SHORT).show();
            }


        } catch (Exception e) {
            System.out.println("Exception here : " + e);
        }
        dialog.dismiss();
        return "Executed";
    }
    @Override
    protected void onPostExecute(String result){

        if(valid.equalsIgnoreCase("Invalid")){
            Log.d("Registration: ", "Error generated");
            String code = errorcode.replace("Invalid","");
            Toast.makeText(Register.this, "Registration failed: " + code, Toast.LENGTH_SHORT).show();
        }else{
            Toast.makeText(Register.this, "Registration successful", Toast.LENGTH_SHORT).show();
            startActivity(new Intent(Register.this, HomeScreen.class));
            finish();
        }
    }
}

PHP Side

<?php 
// Connecting to database
$connect = $_SERVER['DOCUMENT_ROOT'];
$connect .= "pathtoconnect.php";
include_once($connect);

// Get all the variables being passed from the APK
$username = mysql_real_escape_string($_POST['username']);
$password1 = mysql_real_escape_string($_POST['password1']);
$password2 = mysql_real_escape_string($_POST['password2']);
$email = mysql_real_escape_string($_POST['userEmail']);
$newsletter = mysql_real_escape_string($_POST['newsletter']);
$pass = 1;
$error = false;

// Check if the username is valid. 
if (preg_match('/[^0-9a-z-_]/i', $username) == 1) {
    $error = 'You can not use spaces or strange characters in a usermame.';
    $pass = 0;      
}
if(strlen($username) < 5) { // Ensure the length is at least 5
    $error = 'Username must be at least 5 characters.';
    $pass= 0 ;
}
if(strlen($password1) < 5) { // Ensure the length is at least 5
    $error = 'Passwords have to be at least slightly challenging (5+ characters).';
    $pass= 0 ;
}

if($password1 != $password2) { // Check for passwords to match
    $error = "Your passwords did not match. Please try again.";
    $pass= 0 ;  
}

if (!filter_var($email, FILTER_VALIDATE_EMAIL)) { // Check to make sure email address is valid
    $error = "The email address you entered is not valid. Double check it.";
    $pass= 0 ;
}

// check if username or email is already in use
$checking = mysql_query("SELECT COUNT(user_id) AS total FROM users WHERE username='$username' OR email='$email'");
$checking = mysql_fetch_array($checking);
if($checking['total'] > 0) {
    $error = 'The username or email you are trying to use is already in use. Please go to the website if you forgot your password to reset it.';    
    $pass= 0 ;
}
if(!$error) {
    echo 'success';
    $time = time();
    mysql_query("INSERT INTO users (username, password, email, date_created, subscription) VALUES ('$username', md5('$password1'), '$email',  '$time', '$subscribe')"); 


    }
else {
    echo 'Invalid'.$error;  
}

?>

The device is reporting the duplicate error and as I mentioned, the data gets inserted so its like 'success' isn't getting echoed. Below is the logs from the JAVA file that show its only getting the failed response.

02-04 22:31:37.442  26159-26159/com.demo D/Registration:﹕ Button Pressed
02-04 22:31:37.862  26159-26559/com.demo D/Registration:﹕ Executing Post
02-04 22:31:37.862  26159-26559/com.demo D/Registration:﹕ Registration failed
02-04 22:31:37.872  26159-26159/com.demo D/Registration:﹕ Error generated

I built a basic html form to pass the data and that method works well, executes the php onces so I'm at a loss. Android/JAVA is new to me so is this the wrong route to accomplish this?

Thanks

you are calling "httpclient.execute(..)" twice:

HTTPRESPONSE = httpclient.execute(HTTPPOST);
ResponseHandler<String> responseHandler = new BasicResponseHandler();
final String response = httpclient.execute(HTTPPOST, responseHandler);

remove one of them should solve your issue :)

You don't need to call your AsynTask subclass (RegisterUser) into a Thread because it is a Thread itselt, that runs out of the main IU Thread. Just call execute method.

Instead of doing:

new Thread(new Runnable() {
            public void run() {
                new RegisterUser().execute("");
            }
        }).start();

Do:

                new RegisterUser().execute("");

May be it could fix the problem.

Also, you are calling execute method twice from DefaultHttpClient object, first and third lines:

HTTPRESPONSE = httpclient.execute(HTTPPOST);
ResponseHandler<String> responseHandler = new BasicResponseHandler();
final String response = httpclient.execute(HTTPPOST, responseHandler);

Its not really an answer, but I converted the code to use JSON request instead of the httppost method and it works much better.

Log.d("JSON", "Running the JSON script");
            JSONObject json = jsonParser.makeHttpRequest(url_register, "POST", params);

            //Getting specific Response
            try {
                RESPONSE_STATUS = json.getInt("success");
                RESPONSE_MESSAGE = json.getString("message");

            } catch (JSONException e) {
                RESPONSE_MESSAGE = "An error has occured during the registration";
                e.printStackTrace();
            }
            Log.d("JSON", json.toString());
            Log.d("Registration: ", "Response Status: " + RESPONSE_STATUS);
            Log.d("Registration: ", "Response: " + RESPONSE_MESSAGE);

            // Redirect the user depending on the response
            if (RESPONSE_STATUS == 1) {
                Log.d("Registration: ", "Registration successful");
                valid = "Successful";
            } else {
                Log.d("Registration: ", "Registration failed");
                valid = "Invalid";
            }

This did take a complete re-write of the php to change the response code to an array.

Again, this doesn't fix my original issue, but is a working alternative method.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM