Codeigniter

개발 순서는 다음과 같이 진행 하였습니다.

1. 비밀번호 찾기 페이지 이동을 개발합니다.

    //비밀번호 찾기
    public function pwsearch()
    {
        $this->load->view('auth/pwsearch_v');
    }

 

2. 이메일 입력 후 서버에서 이메일 형식에 맞지 않거나 존재 하지 않은 이메일 경우에는 에러 메시지 개발

데이터베이스에서 검색을 해야 합니다..

 function email_exists($email)
    {
       $this->load->database();
        if($email)
        {
            $result=array();
            $sql="select id from users where email = ?";
            $query=$this->db->query($sql, array('email'=>$email));
            $result=@$query->row();
            
            if(!$result)
            {
                $this->form_validation->set_message('email_exists', $email.' 은 존재하지 않는 이메일입니다.');
                return FALSE;
            }else
            {
                return TRUE;                    
            }       

        }else{
            return FALSE;
        }
    }

 

 

3. 랜덤 비밀번호 생성 여기서는 랜덤 문자열을 생성 하였습니다.

_GenerateString() 함수는 원하는 사이즈 만큼 생성 가능하며 여기서는 12자리로 생성하였습니다.


//랜덤 문자열 생성 
    function _GenerateString($length) {
        $characters = "0123456789";
        $characters .= "abcdefghijklmnopqrstuvwxyz";
        $characters .= "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
        $string_generated = "";
        $nmr_loops = $length;
        while ($nmr_loops--) {
            $string_generated .= $characters[mt_rand(0, strlen($characters))];
        }
        return $string_generated;
    }

 

 

 

4. 랜덤으로 생성된 비밀 번호 암호화

MIT 에 개발한 암호화를 사용하였습니다.

https://gist.github.com/aheinze/6293939

$hash_format = sprintf("$2y$%02d$", $cost); 같은 경우 $2y$%02d$ 값을 임의로

변경 해서 사용하면 됩니다.

   function alter($pw, $email){
        $update=array('password'=>$pw);
        $where=array('userid'=>$email);
        $result=@$this->db->update('users', $update, $where);
        return $result;
    }

 

5. 암호화 된 비밀번호를 데이터베이스 모델에서 업데이트를 합니다.

    function alter($pw, $email){
        $update=array('password'=>$pw);
        $where=array('userid'=>$email);
        $result=@$this->db->update('users', $update, $where);
        return $result;
    }

 

6. 변경된 비밀번호를 이메일로 발송합니다.

//변경된 비밀번호 이메일로 발송 
            if($result){
                $this->load->library('email');
                $this->email->from('macaronics@macaronics.net', 'Macaronics', 'macaronics@macaronics.net');
                $this->email->to($email);
                $this->email->subject('비밀번호 변경');
                $html="<h3>변경된 비밀번호 : " .$random . "<h3>
                    <h3><a href='http://macaronics.net/index.php/auth' target='_blank' >로그인 하기</a></h3>";
                $this->email->message($html);
                if(!$this->email->send()){
                    alert("이메일 발송에 실패 하였습니다.", "/");
                    exit;
                }else{
                    alert("이메일로  전송 했습니다.", "/");
                }
            }    

 

 

 

 

전체 소스

컨트롤러  : Auth

<?php
defined('BASEPATH') OR exit('No direct script access allowed');


class Auth extends CI_Controller {
	
	function __construct()
	{
		parent::__construct();
		$this->load->model('auth_m');
		$this->load->helper(array('alert', 'form','url', 'date'));
		$this->load->library(array('script', 'common', 'session','form_validation'));
		$this->load->model('admin_menu01_m');
	}

	/*
	 * 주소에서 메서도가 생략되었을 때 실행되는 기본 메서드
	 * 
	 */	
	public function index()
	{	 
		$this->login();
	}

	/*
	 * 사이트 헤더, 푸터가 자동으로 추가된다.
	 * 
	 */
	public function _remap($method)
	{
		if(method_exists($this, $method))
		{
			$this->{ "{$method}" }();	
		}
	}
	
   //비밀번호 찾기
    public function pwsearch()
    {
        $this->load->view('auth/pwsearch_v');
    }

    public function pwsearchsubmit()
    {
        
        $this->form_validation->set_rules("email", '이메일', 'required|valid_email|callback_email_exists');
        if($this->form_validation->run()==FALSE){
            //폼 검증이 실패했을 경우 또는 일력 페이지
            $this->load->view('/auth/pwsearch_v');
            
        }else{ //폼 검증 성공 했을 경우
            
            //랜덤 비말번호 12자리 생성
            $random=$this->_GenerateString(12);

            //비밀 번호 암호화
            if(!function_exists('password_hash')){ 
                $this->load->helper('password');
            }
            $hash=password_hash($random, PASSWORD_BCRYPT);
            $email=$this->input->post('email', true);
    
            //암호화된 비밀 번호 데이터베이스 업데이트 
            $this->load->model('tank_auth/pw_alter_m');   
            $result=$this->pw_alter_m->alter($hash, $email);
            
            
            //변경된 비밀번호 이메일로 발송 
            if($result){
                $this->load->library('email');
                $this->email->from('macaronics@macaronics.net', 'Macaronics', 'macaronics@macaronics.net');
                $this->email->to($email);
                $this->email->subject('비밀번호 변경');
                $html="<h3>변경된 비밀번호 : " .$random . "<h3>
                    <h3><a href='http://macaronics.net/index.php/auth' target='_blank' >로그인 하기</a></h3>";
                $this->email->message($html);
                if(!$this->email->send()){
                    alert("이메일 발송에 실패 하였습니다.", "/");
                    exit;
                }else{
                    alert("이메일로  전송 했습니다.", "/");
                }
            }    
        }    
    }
    
    //랜덤 문자열 생성 
    function _GenerateString($length) {
        $characters = "0123456789";
        $characters .= "abcdefghijklmnopqrstuvwxyz";
        $characters .= "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
        $string_generated = "";
        $nmr_loops = $length;
        while ($nmr_loops--) {
            $string_generated .= $characters[mt_rand(0, strlen($characters))];
        }
        return $string_generated;
    }
    
    
    function email_exists($email)
    {
       $this->load->database();
        if($email)
        {
            $result=array();
            $sql="select id from users where email = ?";
            $query=$this->db->query($sql, array('email'=>$email));
            $result=@$query->row();
            
            if(!$result)
            {
                $this->form_validation->set_message('email_exists', $email.' 은 존재하지 않는 이메일입니다.');
                return FALSE;
            }else
            {
                return TRUE;                    
            }       

        }else{
            return FALSE;
        }
    }
    
    

 

 

 

모델 : Pw_alter_m.php


<?php if (!defined('BASEPATH')) exit('No direct script access allowed');


class Pw_alter_m extends CI_Model{
    
    function __construct()
    {
        parent:: __construct();    
    }
    
    
    function alter($pw, $email){
        $update=array('password'=>$pw);
        $where=array('userid'=>$email);
        $result=@$this->db->update('users', $update, $where);
        return $result;
    }
    
    
}

 

 

 

 

뷰 : 

pwsearch_v.php

<?php
defined('BASEPATH') OR exit('No direct script access allowed');
?>
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
?>
<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <!-- The above 3 meta tags *must* come first in the head; any other head content must come *after* these tags -->
   <title>Macaronics</title>

    <!-- Bootstrap -->
    <link href="/include/css/bootstrap.min.css" rel="stylesheet">
    <!-- font awesome -->
    <link href="/include/css/font-awesome.min.css" rel="stylesheet">
    <!-- Custom Style -->
    <link href="/include/css/style.css" rel="stylesheet">

    <!-- Bootstrap Social Button -->
    <link href="/assets/lib/bootstrap_social/bootstrap-social.css" rel="stylesheet" >


    <!-- HTML5 shim and Respond.js for IE8 support of HTML5 elements and media queries -->
    <!-- WARNING: Respond.js doesn't work if you view the page via file:// -->
    <!--[if lt IE 9]>
      <script src="https://oss.maxcdn.com/html5shiv/3.7.2/html5shiv.min.js"></script>
      <script src="https://oss.maxcdn.com/respond/1.4.2/respond.min.js"></scri.row>.containerpt>
    <![endif]-->

  <!-- jQuery (necessary for Bootstrap's JavaScript plugins) -->
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
  <!-- Include all compiled plugins (below), or include individual files as needed -->
  <script src="/include/js/bootstrap.min.js"></script>
 
<script type="text/javascript" src="https://static.nid.naver.com/js/naverLogin_implicit-1.0.3.js" charset="utf-8"></script>
  

</head>
  <body>
    <div class="container">
      <div class="row">
      
        <div class="col-md-4">
        </div>  
        <div class="col-md-4">
              <div class="page-header">
                  <h2><a href="/">Macaronics</a></h2>
                </div>
          <div class="login-box well">
       
        <?php 
            $attribute=array(
                    'accept-charset'=>"UTF-8",
                    'role'=>"form",
                    'id'=>'auth_login',
                    'method' =>'post'
            );
            echo form_open('/index.php/auth/pwsearchsubmit',$attribute);
            
        ?>  
 
            <legend>비밀번호 찾기</legend>                  
            <div class="form-group">
                <label for="email">이메일(아이디)</label>
                <input name="email" value='<?php echo set_value("email"); ?>' id="email" placeholder="이메일" type="email" class="form-control" />
            </div>
             <div class="form-group">
                <label for="username-email" style="color:red;"><?php if(form_error('email')){echo form_error('email');} else{ echo '';} ?></label>
            </div>
            <div class="form-group">
                <input type="submit" class="btn btn-default btn-login-submit btn-block m-t-md" value="전송" />
            </div>
           
            
        </form>
                
    
          </div>
          <div class="col-md-4">
         </div> 
        </div>
      </div>
    </div>



  
  </body>
  </html>   

 

 

 

 

 

 

 

about author

PHRASE

Level 60  머나먼나라

술과 색과 재물과 기(氣)의 네 가지로 쌓은 담 안에 수많은 어진 자와 어리석은 자가 집안에 들어찼다. 만약 이 세상 사람들이 이곳을 뛰쳐나올 수 있다면, 그것이 바로 신선의 죽지 않는 방법이다. -명심보감

댓글 ( 4)

댓글 남기기

작성