」工欲善其事,必先利其器。「—孔子《論語.錄靈公》
首頁 > 程式設計 > 如何透過驗證令牌在 PHP 中設定電子郵件驗證:完整指南

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

發佈於2024-09-01
瀏覽:687

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]刪除
最新教學 更多>
  • 如何使用 mysqli_pconnect() 在 PHP 中實作 MySQL 連線池?
    如何使用 mysqli_pconnect() 在 PHP 中實作 MySQL 連線池?
    MySQL 的 PHP 連線池在 PHP 中,維護資料庫連線會影響效能。為了優化這一點,開發人員經常考慮使用連接池技術。 MySQL 的連線池MySQL 沒有內建的連線池機制。然而,MySQLi 擴充功能提供了mysqli_pconnect() 函數,其作用與mysqli_connect() 類似,...
    程式設計 發佈於2024-11-07
  • 將 HTMX 加入 GO
    將 HTMX 加入 GO
    HTMX 是 intercooler.js 的後繼者,用於使用 HTTP 指令擴充 HTML,而無需編寫 API。現在,我知道一開始我說我要刪除抽象層,但是我更多的是系統/工具程式設計師,所以我仍然需要一些抽象,直到我掌握了底層實際發生的情況。 基本概念 HTMX 部署 AJAX ...
    程式設計 發佈於2024-11-07
  • 發現 itertools
    發現 itertools
    Itertools 是最有趣的 Python 函式庫之一。它包含一系列受函數式語言啟發的函數,用於與迭代器一起使用。 在這篇文章中,我將提到一些最引起我注意並且值得牢記的內容,以免每次都重新發明輪子。 數數 好幾次我都實現了無限數(好吧,結束了 明確地在某一點用中斷)使用 whi...
    程式設計 發佈於2024-11-07
  • 為什麼每個人都應該學習 Go(即使您認為生活中不需要另一種語言)
    為什麼每個人都應該學習 Go(即使您認為生活中不需要另一種語言)
    啊,Go,编程语言。您可能听说过,也许是从办公室里一位过于热情的开发人员那里听说过的,他总是不停地谈论他们的 API 现在有多“快得惊人”。当然,您已经涉足过其他语言,也许您会想:“我真的需要另一种语言吗?”剧透警报:是的,是的,你知道。 Go 就是那种语言。让我以最讽刺、最真诚的方式为你解释一下。...
    程式設計 發佈於2024-11-07
  • 如何計算 Pandas 中多列的最大值?
    如何計算 Pandas 中多列的最大值?
    在Pandas 中尋找多列的最大值假設您有一個包含多列的資料框,並且希望建立一個包含兩個或多個列中的最大值的新列現有的列。例如,給定A 列和B 列,您需要建立C 列,其中:C = max(A, B)要完成此任務:使用max 函數和axis=1 計算指定列中每行的最大值:df[["A&quo...
    程式設計 發佈於2024-11-07
  • 如何在 PHP 中從目錄中檢索檔案名稱?
    如何在 PHP 中從目錄中檢索檔案名稱?
    從 PHP 中的目錄中擷取檔案如何在 PHP 中存取目錄中的檔案名稱?事實證明,確定正確的命令具有挑戰性。這個問題旨在為尋求類似解決方案的個人提供幫助。 PHP提供了幾種從目錄獲取文件清單的方法:DirectoryIterator(建議)此類允許對目錄中的文件進行迭代:foreach (new Di...
    程式設計 發佈於2024-11-07
  • 使用 Linq、Criteria API 和 Query Over 擴充 NHibernate 的 Ardalis.Specification
    使用 Linq、Criteria API 和 Query Over 擴充 NHibernate 的 Ardalis.Specification
    Ardalis.Specification is a powerful library that enables the specification pattern for querying databases, primarily designed for Entity Framework Cor...
    程式設計 發佈於2024-11-07
  • PYTHON:OOP {初學者版}
    PYTHON:OOP {初學者版}
    Python:物件導向程式設計[OOP]:是一種程式設計範式(模型),使用物件和類別來建立軟體一種模擬現實世界實體和關係的方法。這是基於物件可以包含資料和操作該資料的程式碼的想法。 關於物件導向編程,您需要了解一些關鍵概念: 班級 目的 屬性 方法 遺產 封裝 多態性 抽象 下面的範例是一個幫助您...
    程式設計 發佈於2024-11-07
  • Neo.mjs:一個高效能開源 JavaScript 框架。
    Neo.mjs:一個高效能開源 JavaScript 框架。
    在瀏覽 GitHub 並尋找可協作的開源專案時,我發現了 Neo.mjs。我對這個計畫產生了興趣,並開始更多地研究這個新框架。我想在這篇文章中分享我發現的所有內容。 什麼是 Neo.mjs? Neo.mjs 旨在建立高效能、資料驅動的 Web 應用程序,重點在於利用 Web Wor...
    程式設計 發佈於2024-11-07
  • 將 Azure Functions 部署到 Azure 容器應用程式的兩種方法的比較
    將 Azure Functions 部署到 Azure 容器應用程式的兩種方法的比較
    昨天,我寫了一篇題為「在 Azure 容器應用程式上部署 Java Azure Function」的文章。 在那篇文章中,我提到使用 Azure 的整合管理功能,我想澄清這意味著什麼以及它與本文中先前的方法有何不同。 舊方法:使用 az containerapp create 創...
    程式設計 發佈於2024-11-07
  • 如何使用 MinGW 在 Windows 上建置 GLEW?逐步指南。
    如何使用 MinGW 在 Windows 上建置 GLEW?逐步指南。
    使用MinGW 在Windows 上建立GLEW:綜合指南使用GLEW,這是一個無縫整合OpenGL 和WGL 函數的純頭文件庫,使用MinGW 增強Windows 上OpenGL 應用程式的開發。為了使用 MinGW 有效建置 GLEW,需要一組特定的命令和步驟。 首先,建立兩個名為 lib 和 ...
    程式設計 發佈於2024-11-07
  • 如何使用 CSS 創建帶有對角線的雙色調背景?
    如何使用 CSS 創建帶有對角線的雙色調背景?
    使用對角線創建雙色調背景要使用CSS 實現由對角線分為兩部分的背景,請執行以下操作這些步驟:1。建立兩個 Div:建立兩個單獨的 div 來表示兩個背景部分。 2.設定 Div 樣式:將下列 CSS 套用至 div:.solid-div { background-color: [solid co...
    程式設計 發佈於2024-11-07
  • 文件的力量:閱讀如何改變我在 JamSphere 上使用 Redux 的體驗
    文件的力量:閱讀如何改變我在 JamSphere 上使用 Redux 的體驗
    作為開發人員,我們經常發現自己一頭扎進新的庫或框架,渴望將我們的想法變為現實。跳過文件並直接跳到編碼的誘惑很強烈——畢竟,這有多難呢?但正如我透過建立音樂管理平台 JamSphere 的經驗所了解到的那樣,跳過這一關鍵步驟可能會將順利的旅程變成充滿挑戰的艱苦戰鬥。 跳過文檔的魅力 ...
    程式設計 發佈於2024-11-07
  • 如何在PHP多子網域應用中精準控制Cookie域?
    如何在PHP多子網域應用中精準控制Cookie域?
    在PHP 中控制Cookie 域和子域在PHP 中控制Cookie 域和子域建立多子網域網站時,必須控制會話cookie 的網域確保每個子網域的正確會話管理。然而,手動設定網域時,PHP 的 cookie 處理似乎存在差異。 header("Set-Cookie: cookiename=c...
    程式設計 發佈於2024-11-07
  • 如何取得已安裝的 Go 軟體包的完整清單?
    如何取得已安裝的 Go 軟體包的完整清單?
    檢索Go 中已安裝軟體包的綜合清單在多台電腦上傳輸Go 軟體包安裝時,有必要取得詳細的清單所有已安裝的軟體包。本文概述了此任務的簡單且最新的解決方案。 解決方案:利用“go list”與過時的答案相反,當前的建議列出Go 中已安裝的軟體包是使用“go list”命令。透過指定三個文字句點 ('...
    程式設計 發佈於2024-11-07

免責聲明: 提供的所有資源部分來自互聯網,如果有侵犯您的版權或其他權益,請說明詳細緣由並提供版權或權益證明然後發到郵箱:[email protected] 我們會在第一時間內為您處理。

Copyright© 2022 湘ICP备2022001581号-3