php - 由于 PHP 邮件程序,Mysql 插入两条记录,我的前端是 Android 应用程序

标签 php android mysql insert phpmailer

我正在开发一个Android应用程序。基本上,我的应用程序在调用 PHP 文件“register.php”之前首先运行验证码,然后 PHP 文件会将其插入数据库中。注册后,下面的查询会插入一条记录。当我添加phpMailer发送验证邮件时,记录被插入两次。

注册.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);
    }

最佳答案

$mail->send(); 实际上发送邮件并将结果( bool 值)放入 $sent 中,因此 $sent() 没有任何意义,也不执行任何操作(它可能会触发运行时错误)。

PHPMailer 与您的数据库无关;这是你包装它的逻辑,这将是错误的。您的代码仅包含数据库插入调用的单个实例,并且没有循环或重复调用,因此您可能会从应用程序接收多个请求;进行一些记录或在主题行中添加随机数将揭示这一点。

您不需要使用 password_hash 制作自己的盐;它会为您完成此操作并将盐嵌入散列值中,因此您可以替换:

//Get a unique Salt
$salt = getSalt();
//Generate a unique password Hash
$password = password_hash(concatPasswordWithSalt($passwordHash,$salt),PASSWORD_DEFAULT);

与:

$password = password_hash($passwordHash, PASSWORD_DEFAULT);

不会失去任何安全性 - 事实上它可能安全。调用纯文本密码 $passwordHash 和哈希密码 $password 非常令人困惑!

关于php - 由于 PHP 邮件程序,Mysql 插入两条记录,我的前端是 Android 应用程序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56240487/

相关文章:

php - 将 ID 分配给下拉框中的选项并作为 IPN 变量传递

php - 互联网速度对 PHP/MySQL 执行的影响

android - 定期刷新/重新加载 Activity

mysql - 选择数据 MYSQL

c# - .NET 中的嵌入式 Web 服务器

php - typekit.com 是如何运作的? @font-face

android - 您必须使用 ParseObject.create() 或适当的子类创建这种类型的 ParseObject。 - 应用程序崩溃但代码正确

android - 如何在我的 Android 应用程序中集成 PayPal 订阅按钮?

php - 在 PHP 中检查时间在过去 24 小时内

mysql - 删除mysql表中的所有重复项