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

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

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

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]刪除
最新教學 更多>
  • 如何克服PHP的功能重新定義限制?
    如何克服PHP的功能重新定義限制?
    克服PHP的函數重新定義限制在PHP中,多次定義一個相同名稱的函數是一個no-no。嘗試這樣做,如提供的代碼段所示,將導致可怕的“不能重新列出”錯誤。 但是,PHP工具腰帶中有一個隱藏的寶石:runkit擴展。它使您能夠靈活地重新定義函數。 runkit_function_renction_...
    程式設計 發佈於2025-04-15
  • 如何在其容器中為DIV創建平滑的左右CSS動畫?
    如何在其容器中為DIV創建平滑的左右CSS動畫?
    通用CSS動畫,用於左右運動 ,我們將探索創建一個通用的CSS動畫,以向左和右移動DIV,從而到達其容器的邊緣。該動畫可以應用於具有絕對定位的任何div,無論其未知長度如何。 問題:使用左直接導致瞬時消失 更加流暢的解決方案:混合轉換和左 [並實現平穩的,線性的運動,我們介紹了線性的轉換。...
    程式設計 發佈於2025-04-15
  • JavaScript計算兩個日期之間天數的方法
    JavaScript計算兩個日期之間天數的方法
    How to Calculate the Difference Between Dates in JavascriptAs you attempt to determine the difference between two dates in Javascript, consider this s...
    程式設計 發佈於2025-04-15
  • 在PHP中如何高效檢測空數組?
    在PHP中如何高效檢測空數組?
    在PHP 中檢查一個空數組可以通過各種方法在PHP中確定一個空數組。如果需要驗證任何數組元素的存在,則PHP的鬆散鍵入允許對數組本身進行直接評估:一種更嚴格的方法涉及使用count()函數: if(count(count($ playerList)=== 0){ //列表為空。 } 對...
    程式設計 發佈於2025-04-15
  • Express.js中如何訪問POST表單字段?
    Express.js中如何訪問POST表單字段?
    訪問express中的帖子表單字段:指南在使用表單時,訪問express中的post form字段可能是一個簡單的過程。但是,快遞版本的細微變化在方法中引入了一些變化。 從Express 4.16.0開始,訪問的帖子表單字段已通過express.json()和express.urlencoded...
    程式設計 發佈於2025-04-15
  • 為什麼我在Silverlight Linq查詢中獲得“無法找到查詢模式的實現”錯誤?
    為什麼我在Silverlight Linq查詢中獲得“無法找到查詢模式的實現”錯誤?
    查詢模式實現缺失:解決“無法找到”錯誤在銀光應用程序中,嘗試使用LINQ建立錯誤的數據庫連接的嘗試,無法找到以查詢模式的實現。 ”當省略LINQ名稱空間或查詢類型缺少IEnumerable 實現時,通常會發生此錯誤。 解決問題來驗證該類型的質量是至關重要的。在此特定實例中,tblpersoon可能...
    程式設計 發佈於2025-04-15
  • Java的Map.Entry和SimpleEntry如何簡化鍵值對管理?
    Java的Map.Entry和SimpleEntry如何簡化鍵值對管理?
    A Comprehensive Collection for Value Pairs: Introducing Java's Map.Entry and SimpleEntryIn Java, when defining a collection where each element com...
    程式設計 發佈於2025-04-15
  • 如何為PostgreSQL中的每個唯一標識符有效地檢索最後一行?
    如何為PostgreSQL中的每個唯一標識符有效地檢索最後一行?
    postgresql:為每個唯一標識符提取最後一行,在Postgresql中,您可能需要遇到與在數據庫中的每個不同標識相關的信息中提取信息的情況。考慮以下數據:[ 1 2014-02-01 kjkj 在數據集中的每個唯一ID中檢索最後一行的信息,您可以在操作員上使用Postgres的有效效率: ...
    程式設計 發佈於2025-04-15
  • 如何正確使用與PDO參數的查詢一樣?
    如何正確使用與PDO參數的查詢一樣?
    在pdo 中使用類似QUERIES在PDO中的Queries時,您可能會遇到類似疑問中描述的問題:此查詢也可能不會返回結果,即使$ var1和$ var2包含有效的搜索詞。錯誤在於不正確包含%符號。 通過將變量包含在$ params數組中的%符號中,您確保將%字符正確替換到查詢中。沒有此修改,PD...
    程式設計 發佈於2025-04-15
  • Android如何向PHP服務器發送POST數據?
    Android如何向PHP服務器發送POST數據?
    在android apache httpclient(已棄用) httpclient httpclient = new defaulthttpclient(); httppost httppost = new httppost(“ http://www.yoursite.com/script.p...
    程式設計 發佈於2025-04-15
  • 如何使用Regex在PHP中有效地提取括號內的文本
    如何使用Regex在PHP中有效地提取括號內的文本
    php:在括號內提取文本在處理括號內的文本時,找到最有效的解決方案是必不可少的。一種方法是利用PHP的字符串操作函數,如下所示: 作為替代 $ text ='忽略除此之外的一切(text)'; preg_match('#((。 &&& [Regex使用模式來搜索特...
    程式設計 發佈於2025-04-15
  • 在Python中如何創建動態變量?
    在Python中如何創建動態變量?
    在Python 中,動態創建變量的功能可以是一種強大的工具,尤其是在使用複雜的數據結構或算法時,Dynamic Variable Creation的動態變量創建。 Python提供了幾種創造性的方法來實現這一目標。 利用dictionaries 一種有效的方法是利用字典。字典允許您動態創建密鑰並...
    程式設計 發佈於2025-04-15
  • 如何配置Pytesseract以使用數字輸出的單位數字識別?
    如何配置Pytesseract以使用數字輸出的單位數字識別?
    Pytesseract OCR具有單位數字識別和僅數字約束 在pytesseract的上下文中,在配置tesseract以識別單位數字和限制單個數字和限制輸出對數字可能會提出質疑。 To address this issue, we delve into the specifics of Te...
    程式設計 發佈於2025-04-15
  • 如何使用Java.net.urlConnection和Multipart/form-data編碼使用其他參數上傳文件?
    如何使用Java.net.urlConnection和Multipart/form-data編碼使用其他參數上傳文件?
    使用http request 上傳文件上傳到http server,同時也提交其他參數,java.net.net.urlconnection and Multipart/form-data Encoding是普遍的。 Here's a breakdown of the process:Mu...
    程式設計 發佈於2025-04-15
  • 如何使用替換指令在GO MOD中解析模塊路徑差異?
    如何使用替換指令在GO MOD中解析模塊路徑差異?
    在使用GO MOD時,在GO MOD 中克服模塊路徑差異時,可能會遇到衝突,其中3個Party Package將另一個PAXPANCE帶有導入式套件之間的另一個軟件包,並在導入式套件之間導入另一個軟件包。如迴聲消息所證明的那樣: go.etcd.io/bbolt [&&&&&&&&&&&&&&&&...
    程式設計 發佈於2025-04-15

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

Copyright© 2022 湘ICP备2022001581号-3