検証トークンを使用して 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 をインストールするコードを確認します:

composer には phpmailer/phpmailer が必要です

Mailtrap API/SMTP を使用する理由

これは、メールを 1 か所でテスト、送信、制御するためのメール配信プラットフォームです。そして、特に次のことが得られます:

さまざまな言語用の既製の構成設定、PHP と Laravel が含まれています。

主要言語の SMTP と API (OFC、PHP を含む)。 

業界最高の分析。 

27 時間年中無休の人的サポートと、緊急の場合の迅速な手続き。 

これにより、電子メール検証プロセスをブートストラップし、すべての人にとって安全かつ安定した状態に保つことができます。

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 クラスと例外クラスがインポートされます。

  • sendVerificationEmail($email, $verificationCode) は関数定義です。 

  • 新しい PHPMailer オブジェクトが作成されます。 

  • try-catch ブロックは、電子メール送信中の例外を処理します。

  • サーバー設定は、構成例に従って Mailtrap に設定されています。 

  • メールの内容はプレーンテキストの isHTML(false) に設定されます。 

ヒント:

  • メールのコンテンツは HTML にリファクタリングできます。 

  • スループットの制限のため、サインアップ フォーム SMTP リレーとして gmail.com を使用することは避けてください。ただし、本当にメーラー 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 中国語 Web サイトの他の関連記事を参照してください。

ソース:dev.to
このウェブサイトの声明
この記事の内容はネチズンが自主的に寄稿したものであり、著作権は原著者に帰属します。このサイトは、それに相当する法的責任を負いません。盗作または侵害の疑いのあるコンテンツを見つけた場合は、admin@php.cn までご連絡ください。
著者別の最新記事
人気のチュートリアル
詳細>
最新のダウンロード
詳細>
ウェブエフェクト
公式サイト
サイト素材
フロントエンドテンプレート
私たちについて 免責事項 Sitemap
PHP中国語ウェブサイト:福祉オンライン PHP トレーニング,PHP 学習者の迅速な成長を支援します!