PHP邮箱注册验证码功能实现(使用PHPMailer)

前言

本文实现的功能是在网站注册账号时,发送邮箱验证码,并验证邮箱验证码是否正确。下面会对php的邮件发送,验证码验证作详细解说。
样式:
在这里插入图片描述

php使用PHPMailer类进行邮件发送

开始我以为php邮件发送只要使用mail()函数就ok了,但实际操作给了我沉重一击。mail() 函数需要服务器环境支持,而这个环境支持操作很麻烦(对我以及一些使用第三方服务器的来说)。所以我选择了万金油PHPMailer,PHPMailer 是一个 PHP 邮件发送函数包,支持发送 HTML 内容的电子邮件,以及可以添加附件发送,无需搭建复杂的Email服务,相当好用。

这里要说一下PHPMailer的两种版本,一个是稳定版5.2,一个是6.x,5.2的版本不再技术支持兼容php5.0之前的版本,而且已经不更新了(也就是说如果爆出类似之前的远程代码执行,会不安全),6.x的一直在更新,据说bug有点多,经常报错,调试麻烦一点,选哪个看看自己了。具体的在github上可以看:

https://github.com/PHPMailer/PHPMailer/

不管是5的还是6的网上都有使用实例,GitHub文档也很详细。可以参考:

这是5.2的一个使用实例(GitHub上翻译过来的):

<?php
require 'PHPMailerAutoload.php';

$mail = new PHPMailer;

//$mail->SMTPDebug = 3;                               // 启用详细的调试输出

$mail->isSMTP();                                      // 设置邮件使用SMTP 
$mail->Host = 'smtp1.example.com;smtp2.example.com';  // 指定主备用的SMTP服务器
$mail->SMTPAuth = true;                               // 启用SMTP验证
$mail->Username = 'user@example.com';                 // SMTP用户名
$mail->Password = 'secret';                           // SMTP密码
$mail->SMTPSecure = 'tls';                            // 启用TLS加密,`ssl`也接受
$mail->Port = 587;                                    // 要连接的TCP端口
$mail->setFrom('from@example.com', 'Mailer');
$mail->addAddress('joe@example.net', 'Joe User');     // 添加收件人
$mail->addAddress('ellen@example.com');               // 名称是可选的
$mail->addReplyTo('info@example.com', 'Information');
$mail->addCC('cc@example.com');
$mail->addBCC('bcc@example.com');

$mail->addAttachment('/var/tmp/file.tar.gz');         // 添加附件
$mail->addAttachment('/tmp/image.jpg', 'new.jpg');    // 可选名称
$mail->isHTML(true);                                  // 将电子邮件格式设置为HTML

$mail->Subject = '这里是主题';
$mail->Body    = '这是HTML邮件正文<b>粗体!</b>';
$mail->AltBody = '这是在非HTML邮件客户端纯文本';

if(!$mail->send()) {
    echo '无法发送消息.';
    echo '邮件错误: ' . $mail->ErrorInfo;
} else {
    echo '消息已发送';
}

6.x版的(也是GitHub上翻译过来的):

<?php
//将PHPMailer类导入全局名称空间
//这些必须在脚本的顶部,而不是在函数内部
use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\SMTP;
use PHPMailer\PHPMailer\Exception;

// Load Composer的自动加载器
require 'vendor/autoload.php';

// 实例化并传递`true`会启用异常
$mail = new PHPMailer(true);

try {
    //服务器设置
    $mail->SMTPDebug = SMTP::DEBUG_SERVER;                      // 启用详细调试输出
    $mail->isSMTP();                                            // 使用SMTP 
    $mail->Host       = 'smtp1.example.com';                    // 将SMTP服务器设置为通过
    $mail->SMTPAuth   = true;                                   // 启用SMTP验证authentication
    $mail->Username   = 'user@example.com';                     // SMTP用户名
    $mail->Password   = 'secret';                               // SMTP密码
    $mail->SMTPSecure = PHPMailer::ENCRYPTION_STARTTLS;         // 启用TLS加密;`的PHPMailer :: ENCRYPTION_SMTPS`鼓励
    $mail->Port       = 587;                                    // 要连接的TCP端口,对于上面的`PHPMailer :: ENCRYPTION_SMTPS`使用465

    //收件人
    $mail->setFrom('from@example.com', 'Mailer');
    $mail->addAddress('joe@example.net', 'Joe User');     // 添加收件人
    $mail->addAddress('ellen@example.com');               // 名称是可选的
    $mail->addReplyTo('info@example.com', 'Information');
    $mail->addCC('cc@example.com');
    $mail->addBCC('bcc@example.com');

    // 附件
    $mail->addAttachment('/var/tmp/file.tar.gz');         // 添加附件
    $mail->addAttachment('/tmp/image.jpg', 'new.jpg');    // 可选名称

    // 内容
    $mail->isHTML(true);                                  // 将电子邮件格式设置为HTML 
    $mail->Subject = 'Here is the subject';
    $mail->Body    = 'This is the HTML message body <b>in bold!</b>';
    $mail->AltBody = 'This is the body in plain text for non-HTML mail clients';

    $mail->send();
    echo 'Message has been sent';
} catch (Exception $e) {
    echo "Message could not be sent. Mailer Error: {$mail->ErrorInfo}";
}

6.x的autoload.php自动加载器是Composer生成的,并不是PHPMailer所有的,如果不想使用Composer,可以一个一个文件加载,在src文件夹,一个是必须的PHPMailer.php,使用SMTP还需要SMTP.php。如下:

<?php
use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\Exception;

require 'PHPMailer/src/Exception.php';
require 'PHPMailer/src/PHPMailer.php';
require 'PHPMailer/src/SMTP.php';

5.2的可以直接用https://blog.csdn.net/u013416034/article/details/106633895写的封装方法,不过他写的方法debug调试传值错了,是开启的,要修改一下:

<?php
 
require_once 'PHPMailer/class.phpmailer.php';
require_once 'PHPMailer/class.smtp.php';
 
class QQMailer
 
{    
 
    public static $HOST = 'smtp.qq.com'; // QQ 邮箱的服务器地址
 
    public static $PORT = 465; // smtp 服务器的远程服务器端口号
 
    public static $SMTP = 'ssl'; // 使用 ssl 加密方式登录
 
    public static $CHARSET = 'UTF-8'; // 设置发送的邮件的编码
 
 
 
    private static $USERNAME = '123456@qq.com'; // 授权登录的账号
 
    private static $PASSWORD = '****'; // 授权登录的密码
 
    private static $NICKNAME = '小明'; // 发件人的昵称
 
 
 
    /**
     * QQMailer constructor.
     * @param bool $debug [调试模式]     */
 
    public function __construct()
 
    {
 
            $this->mailer = new PHPMailer();        
 
            $this->mailer->SMTPDebug = 0;        
 
            $this->mailer->isSMTP(); // 使用 SMTP 方式发送邮件    
	}    
 
    /**
     * @return PHPMailer     
     **/
 
    public function getMailer()
		
    {       
		return $this->mailer;
 
    }   
	private function loadConfig()
		
    {        /* Server Settings  */
 
        $this->mailer->SMTPAuth = true; // 开启 SMTP 认证
 
        $this->mailer->Host = self::$HOST; // SMTP 服务器地址
 
        $this->mailer->Port = self::$PORT; // 远程服务器端口号
 
        $this->mailer->SMTPSecure = self::$SMTP; // 登录认证方式
 
        /* Account Settings */
 
        $this->mailer->Username = self::$USERNAME; // SMTP 登录账号
 
        $this->mailer->Password = self::$PASSWORD; // SMTP 登录密码
 
        $this->mailer->From = self::$USERNAME; // 发件人邮箱地址
 
        $this->mailer->FromName = self::$NICKNAME; // 发件人昵称(任意内容)
 
        /* Content Setting  */
 
        $this->mailer->isHTML(true); // 邮件正文是否为 HTML
 
        $this->mailer->CharSet = self::$CHARSET; // 发送的邮件的编码   
	}    
	/**
 
     * Add attachment
 
     * @param $path [附件路径]     
	 
	*/
 
    public function addFile($path)
 
    {        $this->mailer->addAttachment($path);
 
    }    
	
	/**
     * Send Email
     * @param $email [收件人]
     * @param $title [主题]
     * @param $content [正文]
     * @return bool [发送状态]     
	 */
 
    public function send($email, $title, $content)
 
    {   
		$this->loadConfig();        
		
		$this->mailer->addAddress($email); // 收件人邮箱
 
        $this->mailer->Subject = $title; // 邮件主题
 
        $this->mailer->Body = $content; // 邮件信息
 
        return (bool)$this->mailer->send(); // 发送邮件    
	}
    }
?>
<?php
require_once 'QQMailer.php';				
 
QQMailer$mailer = new QQMailer(true);		// 实例化 
 
//$mailer->addFile('');			// 添加附件
 
$title = '123456';			// 邮件标题			
 
$content = 123456;								// 邮件内容
 
$mailer->send('123456@qq.com', $title, $content);           // 发送QQ邮件
?>

点击获取验证码

这个时候可以把功能做的很精致,但我比较粗糙一点,相关表单代码(style就不给了):

<input type="email" name="email" id="email" />  //电子邮箱的输入框

<input type="text" name="code" id="code" />     //验证码的输入框

<input type="button" name="code1" value="点击获取验证码" id="code1" οnclick="sub();sendCode();settime(this);" />  //获取验证码的按钮

获取验证码的按钮我只写了三个js的函数:

//判断电子邮箱是否为空
function sub(){
	var email = document.getElementById("email").value
	if(email == "")
				{
					alert("请输入邮箱账号");
					exit;
				}
}

//120秒倒计时
var countdown=120; 
function settime(btn) {
    if (countdown == 0)
	{ 
    btn.removeAttribute("disabled");  
    btn.value="点击获取验证码"; 
    countdown = 120; 
    return;
  }else
  { 
    btn.setAttribute("disabled", true); 
    btn.value="重新发送(" + countdown + ")"; 
    countdown--; 
  }
setTimeout(function() { 
    settime(btn);
  } ,1000);
}	

//发送电子邮箱账号到后台
 function sendCode() {
  
            $.ajax({
                url: "sendcode.php",
                type: 'POST',
                data: {email:$("#email").val()},
                dataType: 'JSON',
             // success: function (data) {
			 // alert(data.code);
			 // }
            });
        }

第三个函数使用了Ajax,记得需要导入jquery类库。

然后是后台接收电子邮箱账号后发送验证码:

<?php
	
if(isset($_POST['email']) && filter_var($_POST['email'], FILTER_VALIDATE_EMAIL))
	{
	$email = $_POST['email'];
	require_once 'QQMailer.php';	 
	$mailer = new QQMailer(true);		// 实例化 
	$title = '您的验证码';   			// 邮件标题
	$code = rand(10000000,99999999);	//生成验证码
	session_start();
	$_SESSION["emailcode"] = $code;
	$content = $code;       			// 邮件内容
	$mailer->send($email, $title, $content);// 发送QQ邮件
	}else{
?>
	<script type="text/javascript">
	alert("请填写正确的电子邮箱");
	window.location.href = "register.php";
</script>
<?php
}
?>

使用session验证,上面已经将验证码的值设置为session了,在表单接收页面加上:

<?php
$code = $_POST['code'];

if($code != $_SESSION['emailcode']){
?>
	
<script>
	alert("验证码错误");
	window.location.href = "register.php";
</script>
	
<?php
	exit();
}
?>

看完是不是觉得这个功能超简单,感觉真的是做的很精简了(当然并没有怎么考虑安全问题,毕竟太麻烦了!!)

  • 8
    点赞
  • 32
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
抱歉,我不能提供任何非法或侵犯隐私的资源下载链接。如果您需要编写 PHP 邮箱验证码注册的代码,我可以为您提供一些指导和建议。 首先,您需要一个能够发送电子邮件的 SMTP 服务器。您可以使用 PHPMailer 库或 SwiftMailer 库来发送电子邮件。这些库都提供良好的文档和使用示例。 接下来,您需要生成随机的验证码并将其存储在数据库中。在用户提交表单时,您可以验证用户输入的验证码是否与您在数据库中存储的验证码相匹配。 以下是一个简单的 PHP 邮箱验证码注册的示例代码: ```php <?php // 连接数据库 $mysqli = new mysqli("localhost", "username", "password", "database"); if ($mysqli->connect_errno) { echo "Failed to connect to MySQL: " . $mysqli->connect_error; exit(); } // 处理表单提交 if ($_SERVER["REQUEST_METHOD"] == "POST") { // 生成随机验证码 $code = rand(100000, 999999); // 发送邮件 require_once "PHPMailer/PHPMailer.php"; $mail = new PHPMailer\PHPMailer\PHPMailer(); $mail->isSMTP(); $mail->SMTPAuth = true; $mail->Host = "smtp.gmail.com"; $mail->Username = "your@gmail.com"; $mail->Password = "your password"; $mail->SMTPSecure = "tls"; $mail->Port = 587; $mail->setFrom("your@gmail.com", "Your Name"); $mail->addAddress($_POST["email"]); $mail->Subject = "Verification Code"; $mail->Body = "Your verification code is: $code"; if (!$mail->send()) { echo "Failed to send email: " . $mail->ErrorInfo; exit(); } // 将验证码存储到数据库中 $stmt = $mysqli->prepare("INSERT INTO verification_codes (email, code) VALUES (?, ?)"); $stmt->bind_param("si", $_POST["email"], $code); if (!$stmt->execute()) { echo "Failed to insert verification code: " . $stmt->error; exit(); } // 重定向到确认页面 header("Location: confirm.php?email=" . urlencode($_POST["email"])); exit(); } ?> <form method="post"> <label for="email">Email:</label> <input type="email" name="email" required> <button type="submit">Send Verification Code</button> </form> ``` 在确认页面中,您可以要求用户输入他们收到的验证码,并验证它是否与数据库中存储的验证码匹配。 ```php <?php // 连接数据库 $mysqli = new mysqli("localhost", "username", "password", "database"); if ($mysqli->connect_errno) { echo "Failed to connect to MySQL: " . $mysqli->connect_error; exit(); } // 处理表单提交 if ($_SERVER["REQUEST_METHOD"] == "POST") { // 验证验证码 $stmt = $mysqli->prepare("SELECT * FROM verification_codes WHERE email = ? AND code = ?"); $stmt->bind_param("si", $_GET["email"], $_POST["code"]); $stmt->execute(); $result = $stmt->get_result(); if ($result->num_rows == 1) { // 验证通过,可以注册用户了 // ... } else { // 验证失败,重新输入验证码 $error = "Invalid verification code."; } } ?> <form method="post"> <label for="code">Verification Code:</label> <input type="text" name="code" required> <?php if (isset($error)): ?> <p><?= $error ?></p> <?php endif ?> <button type="submit">Confirm</button> </form> ``` 请注意,这只是一个简单的示例代码,您需要根据自己的需求进行修改和定制。同时,您需要采取一些安全措施来防止恶意用户尝试发送垃圾邮件或暴力破解验证码

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值