【问题标题】:Random numbers are generated twice when verifying email验证电子邮件时会生成两次随机数
【发布时间】:2019-05-27 23:31:16
【问题描述】:

我是 PHP 新手。我目前正在做电子邮件验证。我的代码应该生成一个随机数,通过电子邮件发送给用户并在用户输入时进行验证。

这是我的代码:

<?php

require 'PHPMailer/PHPMailerAutoload.php';

session_start();

// initializing variables
$email = $_SESSION ['email'];
$user_code = "";
$errors = array();

// generate a four digit random number
$gen_code = strval (rand (10000, 99999));

// send code to user email

// connect to the database
$db = mysqli_connect('localhost', 'root', '', 'register');

// REGISTER USER
if (isset($_POST['email_confirm'])) {

  // receive all input values from the form
  $user_code = mysqli_real_escape_string($db, $_POST['code']);

  // check whether both codes match
  if ($user_code != $gen_code) { array_push($errors, "The codes do not match"); }
  else {
    // set isConfirmed == true
    if (count($errors) == 0) {
        $query = "UPDATE user_database SET isConfirmed = true WHERE email = '$email'";
        mysqli_query($db, $query);
        $_SESSION['email'] = $email;
        header('location: user_details.php');
    }
  }
}
?>

这里email_confirm是我的提交按钮的名称,code是文本框的名称。

第一次加载页面时一切正常。我收到一封带有随机整数的电子邮件。

当我单击提交按钮时,问题就开始了。我收到另一封不同号码的电子邮件,而我已经输入的号码与我从电子邮件中收到的号码不相等。

请帮忙

【问题讨论】:

  • 是你所有的代码,它不发送电子邮件
  • 我没有包含电子邮件发送逻辑,因为代码会很大。由于逻辑有效,我省略了它
  • 好吧,你说它不应该发送电子邮件,所以听起来逻辑不工作。无论如何,没有代码我也无能为力。

标签: php email-verification


【解决方案1】:

如果这是一个更简单的实验性应用程序,您应该在发送到用户确认电子邮件后立即将 gen_code 存储在此会话中。否则,将代码存储在 db 中,并在您的应用程序收到电子邮件确认 POST 请求时检索它,并将用户发送的代码与您存储它的会话或 db 进行比较。

if (isset($_POST['email_confirm'])) { 
    // receive all input values from the form
    $code = $_SESSION['gen_code']; // in case you would wish to store and retrieve code from db, replace this code with one which retrieved from db by email id... SELECT code from user where email=$email
    $user_code = mysqli_real_escape_string($db, $_POST['code']);
    // check whether both codes match
    if ($user_code != $code) { 
        array_push($errors, "The codes do not match");
    } else {
        if (count($errors) == 0) {
            $query = "UPDATE user_database SET isConfirmed = true WHERE email = '$email'"; 
            mysqli_query($db, $query);
            $_SESSION['email'] = $email;
            header('location: user_details.php');
        }
     }
}

【讨论】:

  • 仍然无法正常工作。我收到通知:未定义索引:gen_code
  • 当我向用户发送确认邮件时,您需要将生成代码存储在会话或数据库中。 $_SESSION['gen_code'] = gen_code;
猜你喜欢
  • 1970-01-01
  • 2018-02-01
  • 1970-01-01
  • 1970-01-01
  • 2010-11-10
  • 1970-01-01
  • 2012-07-23
  • 2017-12-31
  • 1970-01-01
相关资源
最近更新 更多