如何透過驗證令牌在 PHP 中設定電子郵件驗證:完整指南

王林
發布: 2024-08-11 20:32:32
原創
320 人瀏覽過

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 = 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.

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.

<?php
function generateVerificationCode($length = 6) {
    $characters = '0123456789';
    $code = '';
    for ($i = 0; $i < $length; $i++) {
        $code .= $characters[rand(0, strlen($characters) - 1)];
    }
    return $code;
}
?>
登入後複製

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.

<?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;
}
登入後複製

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.
<?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中文網其他相關文章!

來源:dev.to
本網站聲明
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板
關於我們 免責聲明 Sitemap
PHP中文網:公益線上PHP培訓,幫助PHP學習者快速成長!