Comment configurer la vérification des e-mails en PHP via un jeton de vérification : guide complet

王林
Libérer: 2024-08-11 20:32:32
original
233 Les gens l'ont consulté

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

电子邮件验证是确保电子邮件地址存在并且可以接收电子邮件的过程。鉴于,电子邮件验证会检查地址格式是否正确;也就是说 - 根据特定标准(例如 UTF-8)编写。

在本文中,我将讨论 PHP 电子邮件验证以及如何将其用于 Web 开发和通过验证令牌进行用户身份验证。文章涉及一些微教程,包括:

  • 带有 Mailtrap 的 PHPMailer 配置

  • 一个简单的 HTML 表单创建

  • 基本电子邮件地址验证

  • 生成令牌和凭证并将其存储在 SQL 数据库中

  • 使用验证令牌发送验证电子邮件

  • 与验证相关的电子邮件测试

所以,让我们开始吧。

设置电子邮件发送

要发送验证电子邮件,您可以使用 PHP 内置的 mail() 函数或像 PHPMailer 这样的库,它提供更多功能和更好的可靠性。

由于我想让本教程尽可能安全且可用于生产,因此我将使用“PHPMailer”。检查通过Composer安装PHPMailer的代码:

作曲家需要 phpmailer/phpmailer

为什么使用 Mailtrap API/SMTP?

这是一个电子邮件传送平台,可在一个地方测试、发送和控制您的电子邮件。而且,除其他外,您还可以获得以下内容:

各种语言的现成配置设置,包括 PHP 和 Laravel。

SMTP 和 API 以及主要语言的 SDK,包括 ofc、PHP。

行业最佳的分析。

27/7 人力支持,以及紧急案件的快速通道程序。

所有这些都可以让您启动电子邮件验证过程,并确保所有人的安全和稳定。

继续使用 Mailtrap 配置 PHPMailer 的设置:

雷雷

这是 PHPMailer 设置:

雷雷

请注意,上面的代码不会发送验证令牌(点击此处跳转到带有验证令牌的代码片段)。这只是如何设置 Mailtrap SMTP 和定义验证功能的示例。以下是要点的快速细分:

  • PHPMailer 和 Exception 类被导入。

  • sendVerificationEmail($email, $verificationCode) 是函数定义。

  • 创建了一个新的 PHPMailer 对象。

  • try-catch 块处理电子邮件发送期间的异常。

  • 服务器设置按照示例配置设置为 Mailtrap。

  • 电子邮件内容设置为 isHTML(false) 为纯文本。

提示:

  • 电子邮件内容可以重构为 HTML。

  • 由于吞吐量限制,您应该避免使用 gmail.com 作为注册表单 SMTP 中继。但如果您确实想创建邮件程序 PHP 文件并通过 Gmail 发送,请查看本教程。

创建注册表

下面是一个简单的注册表单,它包含标题和用户帐户信息(用户名、电子邮件和密码)。

它没有任何 CSS 样式表或 div 类,因为这只是一个示例。

但是,我建议您将这些包含在生产中,并使它们与您品牌的设计语言保持一致。否则,您的表单可能看起来不专业,用户也不愿意参与其中。

雷雷

额外专业提示 - 考虑在表单中使用 JavaScript

如果您想要有关如何创建包含 reCaptcha 的 PHP 联系表单的完整教程,请观看下面的视频⬇️。

  • JS 可以实时验证用户输入,对错误提供即时反馈,无需重新加载页面。

  • 通过在客户端捕获错误,JS 可以减少发送到服务器的无效请求的数量,从而减少服务器负载并提高每个会话的性能。

  • 使用AJAX,JS可以从服务器发送和接收数据,无需重新加载页面,提供更流畅的用户体验。

现在,我将转向电子邮件地址验证。

电子邮件地址验证

这是一个检查域和 MX 记录的简单脚本。它基本上允许您通过执行 MX 查找来验证电子邮件。

雷雷

但是,该脚本不会发送电子邮件以进行用户激活和身份验证。此外,它不在 MySQL 中存储任何数据。

为此,我将在接下来的部分中执行以下操作:

  • 生成验证令牌

  • 创建 PHP MySQL 架构来存储注册表单中的凭据

  • 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));
Copier après la connexion

Method 2

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

Copier après la connexion

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 );
Copier après la connexion

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:'mailtrapclub@gmail.com', 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+test@gmail.com" $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; }
Copier après la connexion

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(); ?>
Copier après la connexion

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!

Ce qui précède est le contenu détaillé de. pour plus d'informations, suivez d'autres articles connexes sur le site Web de PHP en chinois!

source:dev.to
Déclaration de ce site Web
Le contenu de cet article est volontairement contribué par les internautes et les droits d'auteur appartiennent à l'auteur original. Ce site n'assume aucune responsabilité légale correspondante. Si vous trouvez un contenu suspecté de plagiat ou de contrefaçon, veuillez contacter admin@php.cn
Derniers téléchargements
Plus>
effets Web
Code source du site Web
Matériel du site Web
Modèle frontal
À propos de nous Clause de non-responsabilité Sitemap
Site Web PHP chinois:Formation PHP en ligne sur le bien-être public,Aidez les apprenants PHP à grandir rapidement!