Codeigniter

이메일 Email Class

 

users table 에 

register_email_code 컬럼과 register_auth_code 컬럼을 추가한다.

register_email_code  컬럼에 쿠폰생성 함수 등과 같은 코드를 랜덤으로 발생시켜  값을 넣고 register_auth_code 에는 

기본 값으로 0을 넣고 이메일로 인증이 되면 1 로 만든다.

CREATE TABLE `users` (
  `id` int(11) NOT NULL,
  `auth_code` varchar(10) COLLATE utf8_bin NOT NULL DEFAULT '3' COMMENT '권한',
  `userid` varchar(50) COLLATE utf8_bin NOT NULL COMMENT '아이디',
  `username` varchar(50) COLLATE utf8_bin NOT NULL,
  `nickname` varchar(50) COLLATE utf8_bin NOT NULL COMMENT '별명',
  `password` varchar(255) COLLATE utf8_bin NOT NULL,
  `email` varchar(100) COLLATE utf8_bin NOT NULL,
  `activated` tinyint(1) NOT NULL DEFAULT '1',
  `banned` tinyint(1) NOT NULL DEFAULT '0',
  `ban_reason` varchar(255) COLLATE utf8_bin DEFAULT NULL,
  `new_password_key` varchar(50) COLLATE utf8_bin DEFAULT NULL,
  `new_password_requested` datetime DEFAULT NULL,
  `new_email` varchar(100) COLLATE utf8_bin DEFAULT NULL,
  `new_email_key` varchar(50) COLLATE utf8_bin DEFAULT NULL,
  `last_ip` varchar(40) COLLATE utf8_bin NOT NULL,
  `created` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
  `modified` datetime DEFAULT NULL,
  `icon` varchar(150) COLLATE utf8_bin NOT NULL DEFAULT '/include/dist/img/avatar5.png',
  `register_ip` varchar(30) COLLATE utf8_bin NOT NULL DEFAULT '0',
  `register_email_code` varchar(100) COLLATE utf8_bin DEFAULT NULL,
  `register_auth_code` varchar(1) COLLATE utf8_bin NOT NULL DEFAULT '0' COMMENT '이메일 인증시 1 '
) ENGINE=MyISAM DEFAULT CHARSET=utf8 COLLATE=utf8_bin;

 

//register_email_code  이메일 인증 코드 생성한다.
                    
 $register_email_code=$this->_coupon_generator();

기존에 생성된 번호인지 확인 처리를 한다. 중복코드가 아니면 while 문을 빠져 나온다.

번호는 다음과 같이 생성 된다.  ex ) PWWS-LNDB-URTD-78YRRS3H-NX3R-RBCZ-6QPK

컨트롤러 Register.php


        // 쿠폰번호 생성함수
        function _coupon_generator()
        {
            $len = 32;
            $chars = 'ABCDEFGHJKLMNPQRSTUVWXYZ123456789';
        
            srand((double)microtime()*1000000);
        
            $i = 0;
            $str ='';
            while(true){
                 
                    while ($i < $len) {
                        $num = rand() % strlen($chars);
                        $tmp = substr($chars, $num, 1);
                        $str .= $tmp;
                        $i++;
                    }
                    $str = preg_replace('/([0-9A-Z]{4})([0-9A-Z]{4})([0-9A-Z]{4})([0-9A-Z]{4})/', '\1-\2-\3-\4', $str);
                    //DB에 중복 코드 존재 하는지 확인
                    
                    $sql="select * from users where register_email_code =? " ;
                    $query=$this->db->query($sql, array('0' => $str));
                    if($query->num_rows() ==0)break;
            }             
             
            return $str; 
        }

 

config 에 emali.php 파일 생성 후 다음 코드를 카피한다.

 

email.php

<?php defined('BASEPATH') OR exit('No direct script access allowed.');
$config['useragent']        = 'PHPMailer';              // Mail engine switcher: 'CodeIgniter' or 'PHPMailer'
$config['protocol']         = 'mail';                   // 'mail', 'sendmail', or 'smtp'
$config['mailpath']         = '/usr/sbin/sendmail';
$config['smtp_host']        = 'localhost';
$config['smtp_user']        = '';
$config['smtp_pass']        = '';
$config['smtp_port']        = 25;
$config['smtp_timeout']     = 30;                       // (in seconds)
$config['smtp_crypto']      = '';                       // '' or 'tls' or 'ssl'
$config['smtp_debug']       = 0;                        // PHPMailer's SMTP debug info level: 0 = off, 1 = commands, 2 = commands and data, 3 = as 2 plus connection status, 4 = low level data output.
$config['smtp_auto_tls']    = true;                     // Whether to enable TLS encryption automatically if a server supports it, even if `smtp_crypto` is not set to 'tls'.
$config['smtp_conn_options'] = array();                 // SMTP connection options, an array passed to the function stream_context_create() when connecting via SMTP.
$config['wordwrap']         = true;
$config['wrapchars']        = 76;
$config['mailtype']         = 'html';                   // 'text' or 'html'
$config['charset']          = UTF-8;                     // 'UTF-8', 'ISO-8859-15', ...; NULL (preferable) means config_item('charset'), i.e. the character set of the site.
$config['validate']         = true;
$config['priority']         = 3;                        // 1, 2, 3, 4, 5; on PHPMailer useragent NULL is a possible option, it means that X-priority header is not set at all, see https://github.com/PHPMailer/PHPMailer/issues/449
$config['crlf']             = "\n";                     // "\r\n" or "\n" or "\r"
$config['newline']          = "\n";                     // "\r\n" or "\n" or "\r"
$config['bcc_batch_mode']   = false;
$config['bcc_batch_size']   = 200;
$config['encoding']         = '8bit';                   // The body encoding. For CodeIgniter: '8bit' or '7bit'. For PHPMailer: '8bit', '7bit', 'binary', 'base64', or 'quoted-printable'.
// DKIM Signing
// See https://yomotherboard.com/how-to-setup-email-server-dkim-keys/
// See http://stackoverflow.com/questions/24463425/send-mail-in-phpmailer-using-dkim-keys
// See https://github.com/PHPMailer/PHPMailer/blob/v5.2.14/test/phpmailerTest.php#L1708
$config['dkim_domain']      = '';                       // DKIM signing domain name, for exmple 'example.com'.
$config['dkim_private']     = '';                       // DKIM private key, set as a file path.
$config['dkim_private_string'] = '';                    // DKIM private key, set directly from a string.
$config['dkim_selector']    = '';                       // DKIM selector.
$config['dkim_passphrase']  = '';                       // DKIM passphrase, used if your key is encrypted.
$config['dkim_identity']    = '';                       // DKIM Identity, usually the email address used as the source of the email.

 

컨트롤러 Register.php

유저를 등록 후 등록에 성공하면 이메일 발송한다.

html 형식으로 발송 되는데. 텍스트 형식로 전송시 email.php 에서 $config['mailtype'] 를 변경 하면 된다.

		
			$register_email_code=$this->_coupon_generator();
            $toEmail=$this->input->post('email',TRUE);
            
			//register_ip
			$auth_data=array(
				'userid' =>$this->input->post('userid',TRUE),
				'nickname' =>$this->input->post('nickname',TRUE),
				'email' =>$toEmail,
				'password' =>$hash,
				'register_email_code'=>$register_email_code,
				'register_ip'=>$_SERVER['REMOTE_ADDR']
			);
			
			$result=$this->auth_m->register_insert($auth_data);
		
        
	        if($result){
    
                $this->load->library('email');   
                $this->email->from('macaronics@macaronics.net', 'Macaronics', 'macaronics@macaronics.net');
                $this->email->to($toEmail);
             
                $this->email->subject('이메일 인증');
                
                $emailText="<h2><a href='http://macaronics.net/index.php/user/register/email_auth?authcode=".$register_email_code."'>이메일 인증</a></h2> "; ;

                $this->email->message($emailText);
        
                $result=$this->email->send();
                if(!$result){
                    alert('이메일 발송 실패' , '/');
                    exit;
                }
               
                alert('회원가입 되었습니다. 로그하려면 이메일 인증이 필요합니다.' , '/');

 

 

컨트롤러 Register.php

링크 클릭시 아래 주소로 이동해서 이메일 인증 처리가 된다. 인증 되면 register_auth_code를 1로 업데이트 한다.

http://macaronics.net/index.php/user/register/email_auth?authcode=

//이메일 인증
    public function email_auth()
    {
     
        $authcode=$this->input->get('authcode', TRUE);    
        $sql="select * from users  where register_email_code =? and register_auth_code= 0";
        $query=$this->db->query($sql, array('0'=>$authcode));
         
               
        $message['authcode']=$authcode;
        if($query->num_rows() >0){ //인증 대기 상태  코드 존재
   
                $message['message']="인증에 실패 하였습니다."; 
            
               //register_auth_code 를 1 로 업데이트       
                $arrayData=array( 'register_auth_code'=>'1'); 
               $where=array('register_email_code'=>$authcode) ;
               $result=$this->db->update('users', $arrayData, $where);
               
               if($result){
                 $message['message']="인증에 성공 하였습니다.";    
               }else{
                   $message['message']="인증에 실패 하였습니다.";
               }
   
        }else{
           $message['message']="잘못된 접근입니다."; 
        }
       
        $this->load->view('welcome',$message);    
    }
		
    

 

 

 

 

로그인시 인증된 이메일 지 확인 처리 한다.

Auth.php

 public function login()

 //이메일 아직 인증 되지 않은 유저 반환 
                        $email_confirm =$this->auth_m->register_auth_code_confirm($auth_data);
                        if($email_confirm ==0){
                            alert('이메일 인증이 아직 안 되었습니다.', '/');
                            return;
                            exit;
                        } 

 

 

 

 

 

 

 

about author

PHRASE

Level 60  머나먼나라

고금의 뛰어난 사람이 남긴 가르침이 있으니 그 가르침을 배워 가기만 하면 반드시 얻는 바가 있다. -서경

댓글 ( 4)

댓글 남기기

작성