电子邮件验证是确保电子邮件地址存在并且可以接收电子邮件的过程。鉴于,电子邮件验证会检查地址格式是否正确;也就是说 - 根据特定标准(例如 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 = new PHPMailer(); $phpmailer->isSMTP(); $phpmailer->Host = 'live.smtp.mailtrap.io'; $phpmailer->SMTPAuth = true; $phpmailer->Port = 587; $phpmailer->Username = 'api'; $phpmailer->Password = 'YOUR_MAILTRAP_PASSWORD';
这是 PHPMailer 设置:
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('youremail@example.com', '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; } }
请注意,上面的代码不会发送验证令牌(单击此处跳转到带有验证令牌的代码片段)。这只是如何设置 Mailtrap SMTP 和定义验证功能的示例。以下是要点的快速细分:
PHPMailer 和 Exception 类已导入。
sendVerificationEmail($email, $verificationCode) 是函数定义。
创建了一个新的 PHPMailer 对象。
try-catch 块处理电子邮件发送期间的异常。
服务器设置按照示例配置设置为 Mailtrap。
电子邮件内容设置为 isHTML(false) 为纯文本。
提示:
电子邮件内容可以重构为 HTML。
由于吞吐量限制,您应避免使用 gmail.com 作为注册表单 SMTP 中继。但如果您确实想创建邮件程序 PHP 文件并通过 Gmail 发送,请查看本教程。
下面是一个简单的注册表单,它包含标题和用户帐户信息(用户名、电子邮件和密码)。
它没有任何 CSS 样式表或 div 类,因为这只是一个示例。
但是,我建议您将这些包含在生产中,并使它们与您品牌的设计语言保持一致。否则,您的表单可能看起来不专业,用户也不愿意参与其中。
<!DOCTYPE html> <html> <head> <title>Register</title> </head> <body> <form action="register.php" method="post"> <label>Username:</label> <input type="text" name="username" required> <br> <label>Email:</label> <input type="email" name="email" required> <br> <label>Password:</label> <input type="password" name="password" required> <br> <input type="submit" name="register" value="Register"> </form> </body> </html>
额外专业提示 - 考虑在表单中使用 JavaScript
如果您想要有关如何创建包含 reCaptcha 的 PHP 联系表单的完整教程,请观看下面的视频⬇️。
JS 可以实时验证用户输入,对错误提供即时反馈,无需重新加载页面。
通过在客户端捕获错误,JS 可以减少发送到服务器的无效请求数量,从而减少服务器负载并提高每个会话的性能。
使用AJAX,JS可以从服务器发送和接收数据,无需重新加载页面,提供更流畅的用户体验。
现在,我将进行电子邮件地址验证。
这是一个用于检查域和 MX 记录的简单脚本。它基本上允许您通过执行 MX 查找来验证电子邮件。
<?php // This method checks if the domain part of the email address has a functioning mail server. $email = "user@example.com"; list($user, $domain) = explode(separator:"@", $email) if (filter_var($email, filter:FILTER_VALIDATE_EMAIL) && getmxrr($domain, &hosts: $mxhosts)){ echo "Valid email address with a valid mail server" . PHP_EOL; } else { echo "Invalid email address or no valid mail server found" . PHP_EOL; }
但是,该脚本不会发送电子邮件以进行用户激活和身份验证。此外,它不在 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.
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.
<?php function generateVerificationCode($length = 6) { $characters = '0123456789'; $code = ''; for ($i = 0; $i < $length; $i++) { $code .= $characters[rand(0, strlen($characters) - 1)]; } return $code; } ?>
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.
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.
<?php require 'vendor/autoload.php'; use PHPMailer\PHPMailer\PHPMailer; use PHPMailer\PHPMailer\SMTP use PHPMailer\PHPMailer\Exception; //Function to generate a random verification code 1 usage function generateVerificationCode($length = 6) { $characters = '0123456789'; $code = ''; for ($i = 0; $i < $length; $i++) { $code .= $characters[rand(0, strlen($characters) - 1)]; } return $code; } // Function to send a verification email using PHPMailer 1 usage function sendVerificationEmail($email, $verificationCode) { $mail = new PHPMailer (exception: true); try { // Server settings $mail ->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; }
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:
<?php $servername = "localhost"; $username = "root"; $password = ""; $dbname = "user_verification"; // Create connection $conn = new mysqli($servername, $username, $password, $dbname); // Check connection if ($conn->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!
以上是如何通过验证令牌在 PHP 中设置电子邮件验证:完整指南的详细内容。更多信息请关注PHP中文网其他相关文章!