admin管理员组

文章数量:1635364

PHP邮箱注册验证码功能实现

  • 前言
    • 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/PHPMailer/PHPMailer/

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

  • http://www.modouwifi/biancheng/15160.html
  • https://blog.csdn/u013416034/article/details/106633895
    https://wwwblogs/songbo236589/articles/8184039.html

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

<?php
require 'PHPMailerAutoload.php';

$mail = new PHPMailer;

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

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

$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';                    // 将SMTP服务器设置为通过
    $mail->SMTPAuth   = true;                                   // 启用SMTP验证authentication
    $mail->Username   = 'user@example';                     // 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', 'Mailer');
    $mail->addAddress('joe@example', 'Joe User');     // 添加收件人
    $mail->addAddress('ellen@example');               // 名称是可选的
    $mail->addReplyTo('info@example', 'Information');
    $mail->addCC('cc@example');
    $mail->addBCC('bcc@example');

    // 附件
    $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/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'; // QQ 邮箱的服务器地址
 
    public static $PORT = 465; // smtp 服务器的远程服务器端口号
 
    public static $SMTP = 'ssl'; // 使用 ssl 加密方式登录
 
    public static $CHARSET = 'UTF-8'; // 设置发送的邮件的编码
 
 
 
    private static $USERNAME = '123456@qq'; // 授权登录的账号
 
    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', $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();
}
?>

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

本文标签: 验证码邮箱功能PHPphpmailer