확인 토큰을 통해 PHP에서 이메일 확인을 설정하는 방법: 전체 가이드

王林
풀어 주다: 2024-08-11 20:32:32
원래의
223명이 탐색했습니다.

How to Set up Email Verification in PHP via a Verification Token: Complete Guide

이메일 확인은 이메일 주소가 존재하고 이메일을 받을 수 있는지 확인하는 프로세스입니다. 반면 이메일 유효성 검사는 주소 형식이 올바른지 확인합니다. 즉, 특정 표준(예: UTF-8)에 따라 작성되었습니다.

이 글에서는 PHP 이메일 확인에 대해 설명하고 이를 웹 개발에 사용하는 방법과 확인 토큰을 통한 사용자 인증에 대해 설명하겠습니다. 이 기사에는 다음을 포함한 몇 가지 마이크로 튜토리얼이 포함되어 있습니다.

  • Mailtrap

  • 을 사용한 PHPMailer 구성
  • 간단한 HTML 양식 생성

  • 기본 이메일 주소 확인

  • SQL 데이터베이스에서 토큰과 자격 증명 생성 및 저장

  • 인증 토큰을 사용하여 이메일 인증 보내기

  • 인증과 관련된 이메일 테스트

자, 그럼 시작해 보겠습니다.

이메일 전송 설정

확인 이메일을 보내려면 PHP에 내장된 mail() 기능이나 더 많은 기능과 더 나은 안정성을 제공하는 PHPMailer와 같은 라이브러리를 사용할 수 있습니다.

튜토리얼을 최대한 안전하고 생산 준비가 되도록 만들고 싶기 때문에 'PHPMailer'를 사용하겠습니다. Composer를 통해 PHPMailer를 설치하는 코드를 확인하세요:

작성기에는 phpmailer/phpmailer가 필요합니다

Mailtrap API/SMTP를 사용하는 이유는 무엇입니까?

한 곳에서 이메일을 테스트, 전송, 제어할 수 있는 이메일 전달 플랫폼입니다. 그리고 무엇보다도 다음과 같은 이점을 얻을 수 있습니다.

다양한 언어, PHP 및 Laravel에 대한 사전 구성 설정이 포함되어 있습니다.

주요 언어, ofc, PHP의 SDK가 포함된 SMTP 및 API가 포함되어 있습니다.

업계 최고의 분석.

27/7 인력 지원 및 긴급 상황에 대한 빠른 처리 절차.

이메일 확인 프로세스를 부트스트랩하고 모두를 위해 안전하고 안정적으로 유지할 수 있는 모든 것입니다.

Mailtrap으로 PHPMailer를 구성하는 설정으로 이동하세요:

으아악

다음은 PHPMailer 설정입니다:

으아악

위의 코드는 확인 토큰을 보내지 않는다는 점에 유의하세요(확인 토큰이 포함된 코드 조각으로 이동하려면 여기를 클릭하세요). 이는 Mailtrap SMTP를 설정하고 확인 기능을 정의하는 방법의 예일 뿐입니다. 주요 사항에 대한 간략한 분석은 다음과 같습니다.

  • PHPMailer 및 예외 클래스를 가져옵니다.

  • sendVerificationEmail($email, $verificationCode)는 함수 정의입니다.

  • 새로운 PHPMailer 객체가 생성되었습니다.

  • try-catch 블록은 이메일 전송 중 예외를 처리합니다.

  • 서버 설정은 예시적인 구성에 따라 Mailtrap으로 설정되어 있습니다.

  • 일반 텍스트의 경우 이메일 내용이 isHTML(false)로 설정됩니다.

팁:

  • 이메일 콘텐츠를 HTML로 리팩터링할 수 있습니다.

  • 처리량 제한으로 인해 gmail.com을 가입 양식 SMTP 릴레이로 사용하지 않는 것이 좋습니다. 그러나 메일러 PHP 파일을 만들고 Gmail을 통해 보내고 싶다면 이 튜토리얼을 확인하세요.

등록 양식 만들기

아래는 간단한 등록 양식으로, 헤더와 사용자 계정 정보(사용자 이름, 이메일, 비밀번호)가 포함되어 있습니다.

이것은 단지 예시이므로 CSS 스타일시트나 div 클래스가 없습니다.

그러나 이러한 사항을 생산에 포함하고 브랜드의 디자인 언어에 맞게 조정하는 것이 좋습니다. 그렇지 않으면 양식이 비전문적으로 보일 수 있으며 사용자는 양식에 참여하기를 꺼릴 것입니다.

으아악

보너스 전문가 팁 - 양식에 JavaScript 사용을 고려해보세요.

reCaptcha가 포함된 PHP 문의 양식을 만드는 방법에 대한 전체 튜토리얼을 보려면 아래 동영상을 확인하세요 ⬇️.

  • JS는 사용자 입력을 실시간으로 검증하여 페이지를 다시 로드할 필요 없이 오류에 대한 즉각적인 피드백을 제공할 수 있습니다.

  • 클라이언트 측에서 오류를 포착함으로써 JS는 서버로 전송되는 잘못된 요청 수를 줄여 서버 부하를 줄이고 각 세션의 성능을 향상시킬 수 있습니다.

  • AJAX를 사용하면 JS는 페이지를 다시 로드하지 않고도 서버에서 데이터를 보내고 받을 수 있어 보다 원활한 사용자 경험을 제공할 수 있습니다.

이제 이메일 주소 인증으로 넘어가겠습니다.

이메일 주소 확인

다음은 도메인과 MX 레코드를 확인하는 간단한 스크립트입니다. 기본적으로 MX 조회를 수행하여 이메일을 확인할 수 있습니다.

으아악

단, 스크립트는 사용자 활성화 및 인증을 위한 이메일을 보내지 않습니다. 또한 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.

로그인 후 복사

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:'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.
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 학습자의 빠른 성장을 도와주세요!