Я занимаюсь разработкой приложения для Android.По сути, мое приложение сначала запускает капчу перед вызовом файла PHP 'register.php', а затем файл PHP вставит его в базу данных.После регистрации по запросу ниже будет вставлена запись.Когда я добавляю phpMailer для отправки письма с подтверждением, запись вставляется дважды.
register.php
<?php
//Tutorial: http://www.androiddeft.com/login-registration-android-php-mysql/#Source_code_and_APK_Files
$response = array();
include 'db/db_connect.php';
include 'functions.php';
require 'phpmailer/src/PHPMailer.php';
require 'phpmailer/src/SMTP.php';
require 'phpmailer/src/Exception.php';
$mail = new PHPMailer\PHPMailer\PHPMailer();
//Enable SMTP debugging.
$mail->SMTPDebug = true;
//Set PHPMailer to use SMTP.
$mail->isSMTP();
//Set SMTP host name
$mail->Host = 'smtp.gmail.com';
//Set this to true if SMTP host requires authentication to send email
$mail->SMTPAuth = true;
//Provide username and password
$mail->Username = "mygmailaccount@gmail.com";
$mail->Password = "my gmail password";
//If SMTP requires TLS encryption then set it
$mail->SMTPSecure = "ssl";
//Set TCP port to connect to
$mail->Port = 465;
//Get the input request parameters
$inputJSON = file_get_contents('php://input');
$input = json_decode($inputJSON, TRUE); //convert JSON into array
$mail->From = "example@gmail.com";
$mail->FromName = "RoadTrip";
$mail->addAddress($emailAddress, "Carl Baldemor");
$mail->isHTML(true);
$mail->Subject = "RoadTrip Account Verification";
$mail->Body = "<i>Please click the link below to verify your account</i>";
$mail->AltBody = "Insert Link here";
$sent = $mail->send();
//Check for Mandatory parameters
if(isset($input['username']) && isset($input['password']) && isset($input['emailAddress']) && isset($input['firstName']) && isset($input['middleName']) && isset($input['lastName']) && isset($input['mobileNumber']) && isset($input['phoneNumber'])){
$username = $input['username'];
$passwordHash = $input['password'];
$emailAddress = $input['emailAddress'];
$firstName = $input['firstName'];
$middleName = $input['middleName'];
$lastName = $input['lastName'];
$mobileNumber = $input['mobileNumber'];
$phoneNumber = $input['phoneNumber'];
$userTypeID = $input['userTypeID'];
//Check if user already exist
if(!userExists($username)){
//Nest IF - Check if email exists
if (!emailExists($emailAddress)){
$sent();
//Get a unique Salt
$salt = getSalt();
//Generate a unique password Hash
$password = password_hash(concatPasswordWithSalt($passwordHash,$salt),PASSWORD_DEFAULT);
$insertQuery = "INSERT INTO user(userTypeID,firstName, middleName, lastName, emailAddress, mobileNumber, phoneNumber, username, password, salt) VALUES (?,?,?,?,?,?,?,?,?,?)";
if($stmt = $con->prepare($insertQuery)){
$stmt->bind_param("ssssssssss",$userTypeID,$firstName,$middleName,$lastName,$emailAddress,$mobileNumber,$phoneNumber,$username,$password,$salt);
$stmt->execute();
$response["status"] = 0;
$response["message"] = "User created";
$stmt->close();
}
} else{
$response["status"] = 1;
$response["message"] = "Email Exists";
}
}
else{
$response["status"] = 2;
$response["message"] = "User exists";
}
}
else{
$response["status"] = 3;
$response["message"] = "Missing mandatory parameters";
}
echo json_encode($response);
?>
зарегистрировать функцию пользователя в Android
private void registerUser() {
displayLoader();
JSONObject request = new JSONObject();
try {
//Populate the request parameters
request.put(KEY_USERNAME, username);
request.put(KEY_PASSWORD, password);
request.put(KEY_FIRST_NAME, firstName);
request.put(KEY_MIDDLE_NAME, middleName);
request.put(KEY_LAST_NAME, lastName);
request.put(KEY_EMAIL_ADDRESS, emailAddress);
request.put(KEY_MOBILE_NUMBER, mobileNumber);
request.put(KEY_PHONE_NUMBER, phoneNumber);
request.put(KEY_USER_TYPE, userTypeID);
} catch (JSONException e) {
e.printStackTrace();
}
JsonObjectRequest jsArrayRequest = new JsonObjectRequest
(Request.Method.POST, register_url, request, new Response.Listener<JSONObject>() {
@Override
public void onResponse(JSONObject response) {
pDialog.dismiss();
try {
//Check if user got registered successfully
if (response.getInt(KEY_STATUS) == 0) {
//Set the user session
Toast.makeText(getApplicationContext(),
response.getString(KEY_MESSAGE), Toast.LENGTH_SHORT).show();
session.loginUser(username,firstName,lastName);
loadDashboard();
}else if(response.getInt(KEY_STATUS) == 1){
Toast.makeText(getApplicationContext(),
response.getString(KEY_MESSAGE), Toast.LENGTH_SHORT).show();
//Display error message if username is already existsing
etEmailAddress.setError("Email Address is already taken!");
etEmailAddress.requestFocus();
}else if(response.getInt(KEY_STATUS) == 2){
Toast.makeText(getApplicationContext(),
response.getString(KEY_MESSAGE), Toast.LENGTH_SHORT).show();
//Display error message if username is already existsing
etUsername.setError("Username is already taken!");
etUsername.requestFocus();
}else{
Toast.makeText(getApplicationContext(),
response.getString(KEY_MESSAGE), Toast.LENGTH_SHORT).show();
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
pDialog.dismiss();
//Display error message whenever an error occurs
Toast.makeText(getApplicationContext(),
error.getMessage(), Toast.LENGTH_SHORT).show();
}
});
// Access the RequestQueue through your singleton class.
MySingleton.getInstance(this).addToRequestQueue(jsArrayRequest);
}