>  기사  >  백엔드 개발  >  PHP는 이메일 확인을 구현합니다.

PHP는 이메일 확인을 구현합니다.

藏色散人
藏色散人원래의
2020-09-30 10:06:406377검색

PHP에서 이메일 확인을 구현하는 방법: 먼저 phpMailer를 다운로드한 다음 프로젝트 루트 디렉터리에 압축을 푼 다음 메일 서버가 필요합니다. 마지막으로 "config.php"에서 이메일 관련 정보를 구성하고 이메일을 보내기 위한 공개 방법을 만듭니다. 그게 다야.

PHP는 이메일 확인을 구현합니다.

추천: "PHP 비디오 튜토리얼"

1. 소개

요구 사항은 사용자가 등록할 때 이메일을 입력해야 한다는 것입니다. 로그인하기 전에 이메일을 확인해야 합니다.

2.

확인 프로세스를 구현합니다. 사용자가 연결을 클릭하면 확인 코드가 사용자의 메일함으로 전송됩니다. 웹사이트로 돌아가서 웹사이트는 인증 코드가 이 사용자 생성 인증 코드인지 확인합니다. 24시간 이내에 계정을 인증해야 합니다. 그렇지 않으면 계정이 무효화됩니다.

1. 준비

이메일을 보내려면 phpMailer 클래스를 추가해야 합니다. phpMailer를 다운로드하고 프로젝트 루트 디렉터리에 추출합니다.

이메일을 보내려면 smtp 프로토콜을 사용하고, 이메일을 받으려면 포트는 25이고, pop3 프로토콜을 사용하고, 포트 번호는 110입니다. 메일 서버도 필요합니다. 직접 제작하거나 타사 제품을 사용할 수 있습니다. 타사 메일 서버를 사용하려면 해당 타사에 계정을 등록해야 합니다. 로그인하고 smtp 프로토콜을 활성화하십시오.

config.php에서 이메일 관련 정보를 구성하세요.

   'EMAIL' => array(

       'host' => 'smtp.163.com',

       'user' => 'youxiangzhanghao',

       'password' => 'password', //此处的密码为user邮箱在开启smtp时设置的授权密码。     

),

2. 이메일 전송을 위한 공개 메소드 생성

/**

 * 发送邮件的方法

 */

functionsendMail($to, $title, $content)

{

         require_once('./PHPMailer-5.2.14/class.smtp.php');

         require_once('./PHPMailer-5.2.14/class.phpmailer.php');

         $mail = new PHPMailer();

         //设置为发送邮件

         $mail->IsSMTP();

         //是否允许发送html代码为邮件内容

         $mail->IsHTML(true);

         $mail->CharSet = 'utf-8';

         //是否需要身份验证

         $mail->SMTPAuth = true;

         //邮件服务器的帐号信息

         $mailConfig = C('EMAIL');

         $mail->From =$mailConfig['user'].'@163.com';

         $mail->FromName =$mailConfig['user'];

         $mail->Host = $mailConfig['host'];

         $mail->Username = $mailConfig['user'];

         $mail->Password =$mailConfig['password'];

         //发邮件的端口号

         $mail->Port = 25;

         //收件人

         $mail->AddAddress($to);

         //邮件标题

         $mail->Subject = $title;

         //邮件内容

         $mail->Body = $content;

         return($mail->send());

}

컨트롤러 홈페이지 메소드에서 테스트

//测试发送邮件

var_dump(sendMail(&#39;haha@163.com&#39;,&#39;phptestemail&#39;, &#39;<a href="http://www.phptest.com">hahahah</a>&#39;));

3. 멤버 테이블 수정, 이메일 필드 및 인증 코드 필드 추가

email  varchar(150)  not  null comment  &#39;邮箱&#39;,

email_chkcode  char(32)  not  null default  &#39;&#39;  comment  &#39;邮箱验证码&#39;,

email_chkcode_time  int  unsigned  not  null comment  &#39;邮箱验证码生成时间&#39;,

key  email_chkcode(email_chkcode)

4. email

등록 양식을 수정하고 이메일 필드를 추가하세요. 이메일 필드 삽입을 허용하도록 회원 모델을 수정하고 이메일 확인 규칙으로 이메일 필드를 추가하세요.

5. 등록 전 이메일 인증 코드 생성

_before_insert() 메소드에서

                   //生成email验证码

                   $data[&#39;email_chkcode&#39;]= md5(uniqid());

                   $data[&#39;email_chkcode_time&#39;]= time();

6. 등록 후 사용자의 이메일로 인증 코드를 보냅니다

         /**

          * 注册后的钩子函数

          */

         protected function _after_insert($data,$option)

         {

                   $content = "欢迎注册,请点击以下完成验证:<p><a href=&#39;http://www.php2.com/eshop/index.php/Home/Member/email_chk/code/{$data[&#39;email_chkcode&#39;]}&#39;>请点击</a></p>";

                   sendMail($data[&#39;email&#39;],&#39;php2网站邮箱验证&#39;, $content);

         }

7.

    /**

     * 完成邮箱验证方法

     */

    public function email_chk()

    {

        //接收验证码

        $code = I(&#39;get.code&#39;);

        //查询这个验证码是否有效

        $member = D(&#39;Admin/Member&#39;);

        $info = $member->field(&#39;id,email_chkcode_time&#39;)->where(array(

            &#39;email_chkcode&#39; => $code,

        ))->find();

        if($info)

        {

            if((time() -$info[&#39;email_chkcode_time&#39;]) > 86400)

            {

                //帐号过期,删除这个帐号

               $member->delete($info[&#39;id&#39;]);

                $this->error(&#39;验证码已过期,帐号已经删除,请重新注册&#39;, U(&#39;regist&#39;));

                exit;

            }

            else

            {

                //验证通过,将验证码清空

                $member->where(array(

                    &#39;id&#39; => $info[&#39;id&#39;],

               ))->setFielf(&#39;email_chkcode&#39;, &#39;&#39;);

                $this->success(&#39;验证通过,请登陆&#39;, U(&#39;login&#39;));

                exit;

            }

        }

        else

        {

            $this->error(&#39;参数错误&#39;, U(&#39;/&#39;));

            exit;

        }

    }

8 .           멤버십 모델에서 로그인 방법을 수정하세요

         //判断这个帐号是否通过验证码验证

         if(!empty($user[&#39;email_chkcode&#39;]))

         {

                   $this->error= &#39;必须验证后才可以登陆&#39;;

                   returnfalse;

         }

9.         계정이 이미 존재하지만 만료되어 확인되지 않은 경우 계정을 삭제할 수 있습니다.

등록 중에 양식 확인을 추가하고 사용자 이름과 이메일에 대한 고유성 및 등록 확인 코드에 대한 확인을 추가하세요.

               배열('email','chk_un_email', '이메일이 이미 존재합니다!', 1,'콜백', 3),

                                                                             array('email',''chk_un_email', ''이메일이 이미 존재합니다!', 1 , '콜백', 3),

                     array(''사용자 이름', ''chk_un_user', '' '사용자 이름이 이미 존재합니다!',                     '콜백', 3),

         //验证已经存在的邮箱是否通过验证

         public function chk_un_email()

         {

                   $email = I(&#39;post.email&#39;);

                   $username =I(&#39;post.username&#39;);

                   $hasEmail =$this->field(&#39;id,email_chkcode,email_chkcode_time&#39;)->where(array(

                            &#39;email&#39; =>$email,

                   ))->find();

                   if($hasEmail)

                   {

                            if(empty($hasEmail[&#39;email_chkcode&#39;]))

                            {

                                     returnfalse;

                            }

                            else

                            {

                                     if(time() -$hasEmail[&#39;email_chkcode_time&#39;] > 86400)

                                     {

                                               $this->delete($hasEmail[&#39;id&#39;]);

                                               returntrue;

                                     }

                                     else

                                     {

                                               returnfalse;

                                     }

                            }

                   }

                   else

                   {

                            return true;

                   }

         }



         //验证已经存在的用户名是否通过验证

         public function chk_un_user()

         {

                   $username =I(&#39;post.username&#39;);

                   $hasUsername =$this->field(&#39;id,email_chkcode,email_chkcode_time&#39;)->where(array(

                            &#39;username&#39; =>$username,

                   ))->find();

                   if($hasUsername)

                   {

                            if(empty($hasUsername[&#39;email_chkcode&#39;]))

                            {

                                     returnfalse;

                            }

                            else

                            {

                                     if(time() -$hasUsername[&#39;email_chkcode_time&#39;] > 86400)

                                     {

                                               $this->delete($hasUsername[&#39;id&#39;]);

                                               returntrue;

                                     }

                                     else

                                     {

                                               returnfalse;

                                     }

                            }

                   }

                   else

                   {

                            return true;

                   }

         }

10 테스트

위 내용은 PHP는 이메일 확인을 구현합니다.의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

성명:
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.