”工欲善其事,必先利其器。“—孔子《论语.录灵公》
首页 > 编程 > 如何通过验证令牌在 PHP 中设置电子邮件验证:完整指南

如何通过验证令牌在 PHP 中设置电子邮件验证:完整指南

发布于2024-09-01
浏览:627

How to Set up Email Verification in PHP via a Verification Token: Complete Guide

Email verification is the process of ensuring an email address exists and can receive emails. Whereas, email validation checks if the address is properly formatted; that is - written according to specific standards (e.g. UTF-8). 

In this article, I’ll talk about PHP email verification and how to use it for web development and user authentication via a verification token. The article involves a few micro tutorials, including:

  • PHPMailer configuration with Mailtrap

  • A simple HTML form creation

  • Basic email address verification 

  • Generating and storing tokens and credentials in an SQL database

  • Sending email verification with a verification token

  • Email testing as related to verification 

So, let’s get to it. 

Setting up email sending

To send verification emails, you can use PHP's built-in mail() function or a library like PHPMailer, which offers more features and better reliability.

Since I want to make the tutorial as safe and production-ready as possible, I’ll be using ‘PHPMailer’. Check the code to install PHPMailer via Composer:

composer require phpmailer/phpmailer

Why use Mailtrap API/SMTP?

It’s an email delivery platform to test, send, and control your emails in one place. And, among other things, you get the following:

Ready-made configuration settings for various languages, PHP & Laravel included.

SMTP and API with SDKs in major languages, ofc, PHP included. 

Industry-best analytics. 

27/7 Human support, and fast track procedure for urgent cases. 

All that allows you to bootstrap the email verification process, and keep it safe and stable for all.

Moving on to the settings to configure PHPMailer with Mailtrap:

$phpmailer = new PHPMailer();
$phpmailer->isSMTP();
$phpmailer->Host = 'live.smtp.mailtrap.io';
$phpmailer->SMTPAuth = true;
$phpmailer->Port = 587;
$phpmailer->Username = 'api';
$phpmailer->Password = 'YOUR_MAILTRAP_PASSWORD';

Here’s the PHPMailer setup:

use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\Exception;

require 'vendor/autoload.php';

function sendVerificationEmail($email, $verificationCode) {
    $mail = new PHPMailer(true);

    try {
        // Server settings
        $mail->isSMTP();
        $mail->Host = 'live.smtp.mailtrap.io';
        $mail->SMTPAuth = true;
        $mail->Username = 'api';
        $mail->Password = 'YOUR_MAILTRAP_PASSWORD';
        $mail->SMTPSecure = PHPMailer::ENCRYPTION_STARTTLS;
        $mail->Port = 587;

        // Recipients
        $mail->setFrom('[email protected]', 'Your Website');
        $mail->addAddress($email);

        // Content
        $mail->isHTML(false);
        $mail->Subject = 'Email Verification';
        $mail->Body    = "Your verification code is: $verificationCode";

        $mail->send();
        return true;
    } catch (Exception $e) {
        return false;
    }
}

Note that the code above doesn’t send the verification token (click here to jump to the code snippet with the verification token). It’s only an example of how to set up Mailtrap SMTP and define the verification function. Here’s a quick breakdown of key points:

  • PHPMailer and Exception classes get imported.

  • sendVerificationEmail($email, $verificationCode) is the function definition. 

  • A new PHPMailer object is created. 

  • The try-catch block handles exceptions during email sending.

  • The server settings are set to Mailtrap as per the exemplary configuration. 

  • The email content is set to isHTML(false) for plain text. 

Tips: 

  • The email content can be refactored to HTML. 

  • Due to throughput limitations, you should avoid using gmail.com as a signup form SMTP relay. But if you really want to create a mailer PHP file and send via Gmail, check this tutorial. 

Creating a registration form

The below is a simple registration form, it contains the header and user account information (username, email, and password). 

It doesn’t have any CSS stylesheet or div class since this is only an example.

However, I’d advise you to include these on production and align them with the design language of your brand. Otherwise, your form may look unprofessional and users would be reluctant to engage with it.

 



    Register



Bonus Pro Tip - Consider using JavaScript with your forms 

If you want a full tutorial on how to create a PHP contact form that includes reCaptcha, check the video below ⬇️. 

  • JS can validate user input in real time, providing immediate feedback on errors without needing to reload the page. 

  • By catching errors on the client side, JS can reduce the number of invalid requests sent to the server, thereby reducing server load and improving performance for each session.

  • Using AJAX, JS can send and receive data from the server without reloading the page, providing a smoother user experience.

Now, I’ll move to email address verification.  

Email address verification

Here’s a simple script to check for the domain and the MX record. It basically allows you to verify email by performing an MX lookup.

However, the script doesn’t send email for user activation and authentication. Also, it doesn’t store any data in MySQL. 

For that, I’ll do the following in the next sections: 

  • Generate a verification token 

  • Create a PHP MySQL schema to store the credentials from the registration form

  • Send the verification email with the token

  • Verify the verification token

Tip: Similar logic can be applied to a logout/login form.

Generating verification token

A verification token is a unique string generated for each user during registration. This token is included in the verification email and there are two methods to generate it.

Method 1

The first method leverages the bin2hex command to create a random token with the parameter set to (random_bytes(50)).

 

$token = bin2hex(random_bytes(50));

Method 2

Alternatively, you can generate the token with the script below. And I’ll be using that script in the email-sending script.

Storing verification token

Before sending the verification email, it’s vital to ensure you properly handle and store user data. I’ll use a simple SQL schema to create the users table and store the generated token in the database along with the user's registration information.

CREATE TABLE users (
    id INT AUTO_INCREMENT PRIMARY KEY,
    username VARCHAR(50) NOT NULL,
    email VARCHAR(100) NOT NULL,
    password VARCHAR(255) NOT NULL,
    token VARCHAR(255) DEFAULT NULL,
    is_verified TINYINT(1) DEFAULT 0
);

Quick breakdown: 

The script above creates a users table with the following columns:

  • id - Unique identifier for each user, automatically incremented.

  • username - The user's username; it cannot be null.

  • email - The user's email address; it cannot be null.

  • password - The user's password (hashed); it cannot be null.

  • token - A verification token, which can be null.

  • is_verified - A flag indicating whether the user is verified (0 for not verified, 1 for verified), with a default value of 0.

Sending verification token 

Overall, the script below is amalgamation of everything previously discussed in the article and it’s designed to: 

  • Generate a random numeric verification code. 

  • Send the verification email to a specified email address using PHPMailer.

  • Configure the email server settings. 

  • Handle potential errors. 

  • Provide feedback on whether the email was successfully sent.

Note that the script is geared towards Mailtrap users and it leverages the SMTP method.

SMTPDebug = SMTP::DEBUG_OFF; // Set to DEBUG_SERVER for debugging
        $mail ->isSMTP();
        $mail ->Host = 'live.smtp.mailtrap.io'; // Mailtrap SMTP server host 
        $mail ->SMTPAuth = true;
        $mail ->Username = 'api'; // Your Mailtrap SMTP username
        $mail ->Password = 'YOUR_MAILTRAP_PASSWORD'; // Your Mailtrap SMTP password
        $mail ->SMTPSecure = PHPMailer::ENCRYPTION_STARTTLS; // Enable TLS encryption
        $email ->Port = 587; // TCP port to connect to

        //Recipients
        $mail->setFrom(address:'[email protected]', name:"John Doe"); //Sender's email and name
        $mail->addAddress($email); // Recipient's email

        //Content
        $mail->isHTML(isHTML:false); //Set to true if sending HTML email
        $mail->Subject = 'Email Verification';
        $mail->Body = "Your verification code is: $verificationCode";

        $mail->send();
        return true;
    }catch (Exception $e) {
        return false;
    }
}

//Example usage
$email = "mailtrapclub [email protected]"
$verificationCode = generateVerificationCode();

if (sendVerificationEmail($email,$verificationCode)){
    echo "A verification email has been sent to $email. Please check your inbox and enter the code to verrify your email." . PHP_EOL;
} else {
    echo "Failed to send the verification email. Please try again later." . PHP_EOL;
}

Verifying verification token

Yeah, the title is a bit circular, but that’s exactly what you need. The script below enables the “verification of verification” flow ? that moves like this:

  • A user hits the verification link.
  • The token gets validated.
  • The user’s email is marked as verified in the database.
connect_error) {
    die("Connection failed: " . $conn->connect_error);
}

if (isset($_GET['token'])) {
    $token = $_GET['token'];

    $stmt = $conn->prepare("SELECT * FROM users WHERE token=? LIMIT 1");    $stmt->bind_param("s", $token);    $stmt->execute();
    $result = $stmt->get_result();
    if ($result->num_rows > 0) {
        $user = $result->fetch_assoc();        $stmt->close();
        $stmt = $conn->prepare("UPDATE users SET is_verified=1, token=NULL WHERE id=?");        $stmt->bind_param("i", $user['id']);

        if ($stmt->execute() === TRUE) {
            echo "Email verification successful!";
        } else {
            echo "Error: " . $conn->error;
        }        $stmt->close();
    } else {
        echo "Invalid token!";
    }
}

$conn->close();
?>

We appreciate you chose this article to know more about php email verification. To continue reading the article and discover more articles on related topics, follow Mailrap Blog!

版本声明 本文转载于:https://dev.to/denyskontorskyy/how-to-set-up-email-verification-in-php-via-a-verification-token-complete-guide-2dmo?1如有侵犯,请联系[email protected]删除
最新教程 更多>
  • 如何解决 Alpine 容器 Go 中 Pingdom API 的 x509 证书问题?
    如何解决 Alpine 容器 Go 中 Pingdom API 的 x509 证书问题?
    x509 Go 中 Pingdom API 的证书问题在利用 pingdom-go 包与 Pingdom API 交互时,容器化应用程序遇到以下问题错误:“获取 https://api.pingdom.com/api/2.1/checks/0:x509:由未知颁发机构签名的证书。”这意味着容器化应用...
    编程 发布于2024-11-07
  • 前端 UI 组件
    前端 UI 组件
    iHateReading 自定义存储库 在过去的一个月里,我制作了很多 UI 组件,这些组件是真实世界的 Web 组件,例如按钮、输入、表单、横幅、画廊 出于多种目的而制造的组件 学习前端并在我所做的事情上变得更好 提高前端开发中编写更好代码的能力(稍后我会解释这意味着什么) 我目...
    编程 发布于2024-11-07
  • 我可以仅使用 .frm 文件恢复 MySQL 数据库吗?
    我可以仅使用 .frm 文件恢复 MySQL 数据库吗?
    使用 .frm 文件恢复 MySQL 数据库执行常规数据库备份时,捕获整个数据库结构和数据至关重要。数据。但是,在某些情况下,用户可能只能访问 .frm 文件,该文件代表表结构,而不是实际数据。在这种情况下,仅使用 .frm 文件恢复数据库及其数据可能具有挑战性。幸运的是,在某些情况下可以从 .fr...
    编程 发布于2024-11-07
  • 在 PHP 中启用或禁用“allow_url_fopen”:评估风险和替代方案
    在 PHP 中启用或禁用“allow_url_fopen”:评估风险和替代方案
    授予或不授予:探索 PHP 中 'allow_url_fopen' 的用法开发者经常请求激活 'allow_url_fopen' 功能在生产服务器上。鉴于当前的网络开发状况,确定此权限是否仍然是必要的或者是否有更好的替代方案至关重要。评估情况做出决定之前,请考虑以下事...
    编程 发布于2024-11-07
  • 如何覆盖 PHP 的 `mail()` 函数中的信封返回地址?
    如何覆盖 PHP 的 `mail()` 函数中的信封返回地址?
    如何在 PHP Mail 中覆盖信封返回地址为了解决使用 PHP 的 mail() 函数设置信封返回地址的问题,这个答案提供了一个简单的解决方案。mail() 函数接受可选的第四个和第五个参数。虽然第四个参数用于设置标头,但第五个参数可用于将选项直接传递给底层的 sendmail 命令。通过在第五个...
    编程 发布于2024-11-07
  • 科技观察 #1
    科技观察 #1
    大家好,这是我上周的技术手表,其中包含很多 #react、一点 #html、一些 #css 和 #npm。 ? https://www.totaltypescript.com/how-to-create-an-npm-package 如何创建 NPM 包 创建、测试和发布 NPM 包(从初始化到发布...
    编程 发布于2024-11-07
  • mysqli_fetch_array() 何时显示错误“期望参数 1 为 mysqli_result,给定布尔值”?
    mysqli_fetch_array() 何时显示错误“期望参数 1 为 mysqli_result,给定布尔值”?
    mysqli_fetch_array() 期望 MySQLi 结果,而不是布尔值在给定的 PHP 代码中,错误“mysqli_fetch_array() 期望参数 1 为mysqli_result, boolean Give" 表示使用 mysqli_query() 的查询执行失败,它返回...
    编程 发布于2024-11-07
  • 子集和问题的 PHP 程序
    子集和问题的 PHP 程序
    子集和问题是计算机科学和动态规划中的经典问题。给定一组正整数和一个目标和,任务是确定是否存在给定集合的子集,其元素之和等于目标和。 子集和问题的PHP程序 使用递归解决方案 例子 <?php // A recursive solution for the subset sum problem ...
    编程 发布于2024-11-07
  • JavaScript 数组方法:综合指南
    JavaScript 数组方法:综合指南
    数组是 JavaScript 中最基本的数据结构之一。使用数组,您可以在单个变量中存储多个值。 JavaScript 提供了许多内置方法来操作数组,使它们具有令人难以置信的通用性。在这篇文章中,我们将探讨所有内置数组方法以及如何在 JavaScript 项目中有效地使用它们。 核心方...
    编程 发布于2024-11-07
  • 高级 T:依赖参数、推断联合以及 Twitter 上的健康交互。
    高级 T:依赖参数、推断联合以及 Twitter 上的健康交互。
    每次我用 TypeScript 写成 Foo 时,我都会感受到失败的沉重。 在一种情况下,这种感觉特别强烈:当函数采用的参数取决于哪个 "mode" 处于活动状态时。 通过一些示例代码更清晰: type Provider = "PROVIDER A" | "PR...
    编程 发布于2024-11-07
  • 如何创建人力资源管理解决方案
    如何创建人力资源管理解决方案
    1. Understanding the Basics of Frappe and ERPNext Task 1: Install Frappe and ERPNext Goal: Get a local or cloud-based instance of ERP...
    编程 发布于2024-11-07
  • 从周五黑客到发布:对创建和发布开源项目的思考
    从周五黑客到发布:对创建和发布开源项目的思考
    从周五补丁破解到发布:对创建和发布开源项目的思考 这是针对初学者和中级开发人员的系列的一部分,通过将他们的想法作为开源项目发布或引起兴趣。 这些想法是有偏见的和个人的。计划发布更多文章。通过分享一些思考,我希望能启发你做自己的项目 思考(此) 作为 Java 开发人员学习 Go l...
    编程 发布于2024-11-07
  • 可以使用 constexpr 在编译时确定字符串长度吗?
    可以使用 constexpr 在编译时确定字符串长度吗?
    常量表达式优化:可以在编译时确定字符串长度吗?在优化代码的过程中,开发人员尝试计算使用递归函数在编译时计算字符串文字的长度。此函数逐字符计算字符串并返回长度。初始观察:该函数似乎按预期工作,在运行时返回正确的长度并生成表明计算发生在编译时的汇编代码。这就提出了一个问题:是否保证length函数会在编...
    编程 发布于2024-11-07
  • 在 Raspberry Pi 上运行 Discord 机器人
    在 Raspberry Pi 上运行 Discord 机器人
    Unsplash 上 Daniel Tafjord 的封面照片 我最近完成了一个软件工程训练营,开始研究 LeetCode 的简单问题,并觉得如果我每天都有解决问题的提醒,这将有助于让我负起责任。我决定使用按 24 小时计划运行的不和谐机器人(当然是在我值得信赖的树莓派上)来实现此操作,该机器人将执...
    编程 发布于2024-11-07
  • 解锁 JavaScript 的隐藏宝石:未充分利用的功能可提高代码质量和性能
    解锁 JavaScript 的隐藏宝石:未充分利用的功能可提高代码质量和性能
    In the ever-evolving landscape of web development, JavaScript remains a cornerstone technology powering countless large-scale web applications. While...
    编程 发布于2024-11-07

免责声明: 提供的所有资源部分来自互联网,如果有侵犯您的版权或其他权益,请说明详细缘由并提供版权或权益证明然后发到邮箱:[email protected] 我们会第一时间内为您处理。

Copyright© 2022 湘ICP备2022001581号-3