PHPでユーザー認証用のメールを送信する方法

*文
リリース: 2023-03-18 09:30:02
オリジナル
4783 人が閲覧しました

Web サイトでは、ユーザーによる悪意のある登録、本人確認、その他の操作を防ぐために電子メール認証を使用する必要がある場合があります。しかし、PHP バックエンドを使用して確認メールを送信するにはどうすればよいでしょうか?この記事では、一連の登録例を使用して、PHP が電子メールを送信する方法を説明します。

ユーザー登録における最も一般的なセキュリティ検証の 1 つは、電子メール検証です。業界の一般的な慣例によれば、電子メール検証は潜在的なセキュリティ リスクを回避するために非常に重要です。ここで、これらのベスト プラクティスについて説明し、PHP で電子メール検証を作成する方法を見てみましょう。

登録フォームから始めましょう:

<form method="post" action="http://mydomain.com/registration/">
    <fieldset>
        <label for="fname">First Name:</label>
        <input type="text" name="fname" required />
    </fieldset>
    <fieldset>
        <label for="lname">Last Name:</label>
        <input type="text" name="lname" required />
    </fieldset>
    <fieldset>
        <label for="email">Last name:</label>
        <input type="email" name="email" required />
    </fieldset>
    <fieldset>
        <label for="password">Password:</label>
        <input type="password" name="password" required />
    </fieldset>
    <fieldset>
        <label for="cpassword">Confirm Password:</label>
        <input type="password" name="cpassword" required />
    </fieldset>
    <fieldset>
        <button type="submit">Register</button>
    </fieldset>
</form>
ログイン後にコピー


次にデータベースのテーブル構造です:

CREATE TABLE IF NOT EXISTS `user` (
    `id` INT(10) NOT NULL AUTO_INCREMENT PRIMARY KEY,
    `fname` VARCHAR(255) ,
    `lname` VARCHAR(255) ,
    `email` VARCHAR(50) ,
    `password` VARCHAR(50) ,
    `is_active` INT(1) DEFAULT &#39;0&#39;,
    `verify_token` VARCHAR(255) ,
    `created_at` TIMESTAMP,
    `updated_at` TIMESTAMP,
);
ログイン後にコピー


フォームが送信されたら、ユーザーの入力を検証し、新しいユーザーを作成する必要があります:

// Validation rules
$rules = array(
    &#39;fname&#39; => &#39;required|max:255&#39;,
    &#39;lname&#39; => &#39;required|max:255&#39;,
    &#39;email&#39; => &#39;required&#39;,
    &#39;password&#39; => &#39;required|min:6|max:20&#39;,
    &#39;cpassword&#39; => &#39;same:password&#39;
);
$validator = Validator::make(Input::all(), $rules);
// If input not valid, go back to registration page
if($validator->fails()) {
    return Redirect::to(&#39;registration&#39;)->with(&#39;error&#39;, $validator->messages()->first())->withInput();
}
$user = new User();
$user->fname = Input::get(&#39;fname&#39;);
$user->lname = Input::get(&#39;lname&#39;);
$user->password = Input::get(&#39;password&#39;);
// You will generate the verification code here and save it to the database
// Save user to the database
if(!$user->save()) {
    // If unable to write to database for any reason, show the error
    return Redirect::to(&#39;registration&#39;)->with(&#39;error&#39;, &#39;Unable to write to database at this time. Please try again later.&#39;)->withInput();
}
// User is created and saved to database
// Verification e-mail will be sent here
// Go back to registration page and show the success message
return Redirect::to(&#39;registration&#39;)->with(&#39;success&#39;, &#39;You have successfully created an account. The verification link has been sent to e-mail address you have provided. Please click on that link to activate your account.&#39;);
ログイン後にコピー

登録後、ユーザーのメールアドレスが認証されるまで、ユーザーのアカウントは無効のままです。この機能は、ユーザーが入力された電子メール アドレスの所有者であることを確認し、スパムや電子メールの不正使用、情報漏洩を防ぐのに役立ちます。

プロセス全体は非常に簡単です。新しいユーザーが作成されると、登録プロセス中にユーザーが入力した電子メール アドレスに確認リンクを含む電子メールが送信されます。ユーザーが電子メール検証リンクをクリックして電子メール アドレスを確認するまで、ユーザーはログインして Web サイト アプリケーションを使用できません。

検証済みリンクについては、注意する必要があることがいくつかあります。検証されたリンクには、ネットワーク攻撃を防ぐために、十分な長さのランダムに生成されたトークンが含まれている必要があります。同時に、複数のユーザーを攻撃する潜在的な危険を回避するために、電子メール検証にはユーザーの一意の識別子も含める必要があります。

それでは、実際に検証リンクを生成する方法を見てみましょう:

// We will generate a random 32 alphanumeric string
// It is almost impossible to brute-force this key space
$code = str_random(32);
$user->confirmation_code = $code;
ログイン後にコピー


この検証が作成されたら、データベースに保存してユーザーに送信します:

Mail::send(&#39;emails.email-confirmation&#39;, array(&#39;code&#39; => $code, &#39;id&#39; => $user->id), function($message)
{
$message->from(&#39;my@domain.com&#39;, &#39;Mydomain.com&#39;)->to($user->email, $user->fname . &#39; &#39; . $user->lname)->subject(&#39;Mydomain.com: E-mail confirmation&#39;);
});
ログイン後にコピー


メール検証の内容:

<!DOCTYPE html>
<html>
    <head>
        <meta charset="utf-8" />
    </head>
    <body>
        <p style="margin:0">
            Please confirm your e-mail address by clicking the following link:
            <a href="http://mydomain.com/verify?code=<?php echo $code; ?>&user=<?php echo $id; ?>"></a>
        </p>
    </body>
</html>
ログイン後にコピー


それでは、それが機能するかどうかを確認してみましょう:

$user = User::where(&#39;id&#39;, &#39;=&#39;, Input::get(&#39;user&#39;))
            ->where(&#39;is_active&#39;, &#39;=&#39;, 0)
            ->where(&#39;verify_token&#39;, &#39;=&#39;, Input::get(&#39;code&#39;))
            ->where(&#39;created_at&#39;, &#39;>=&#39;, time() - (86400 * 2))
            ->first();
if($user) {
    $user->verify_token = null;
    $user->is_active = 1;
    if(!$user->save()) {
        // If unable to write to database for any reason, show the error
        return Redirect::to(&#39;verify&#39;)->with(&#39;error&#39;, &#39;Unable to connect to database at this time. Please try again later.&#39;);
    }
    // Show the success message
    return Redirect::to(&#39;verify&#39;)->with(&#39;success&#39;, &#39;You account is now active. Thank you.&#39;);
}
// Code not valid, show error message
return Redirect::to(&#39;verify&#39;)->with(&#39;error&#39;, &#39;Verification code not valid.&#39;);
ログイン後にコピー


結論:

上記のコードは単なるチュートリアルの例であり、十分にテストされていません。 Web アプリケーションで使用する前にテストしてください。上記のコードは Laravel フレームワークで実行されていますが、他の PHP フレームワークに簡単に移行できます。同時に、確認リンクは 48 時間有効で、その後は期限切れになります。ワークキューを導入すると、期限切れの検証リンクをタイムリーに処理できます。

関連する推奨事項:

php 完全な検証コード コード php 検証コードの生成 php SMS 検証コード php 検証コード コード

php SMS インターフェイスのサンプル コード (入門)

php SMS ゲートウェイ SMS コンテンツにはスペースを含めることはできません、SMS ゲートウェイ SMS コンテンツ_PHP チュートリアル

以上がPHPでユーザー認証用のメールを送信する方法の詳細内容です。詳細については、PHP 中国語 Web サイトの他の関連記事を参照してください。

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