ribbon iwa

Form Register dengan Verifikasi Email Menggunakan CodeIgniter dan SMTP

Selamat malam sobat blogger, kali ini kami akan share bagaimana membuat form register dengan verifikasi email menggunakan CodeIgniter dan SMTP.



Jika kalian belum mendownload file CodeIgniter silahkan kalian bisa download langsung veris terbru pada website resminya. Langsung saja menuju ke inti pembahasannya.

Instal CodeIgniter
Disini kami telah mempunyai hosting sehingga kami telah mempunyai email dan akun SMTP. Disini kami memberi nama file applikasinya dengan nama registeremailci maka konfigurasi yang cocok untuk memanggil filenya pada folder application / config / config.php adalah sebagai berikut. Setiap kalian mengganti nama file applikasinya maka kalian harus mengkonfigurasi sesuai dengan nama file.

 $config['base_url'] = 'https://arman.my.id/blog/registeremailci/'; 

Database
Buat database dengan nama codeignter kemudian masukkan struktur database dibawah ini.
 CREATE TABLE `users` (
  `id` int(11) NOT NULL,
  `email` varchar(100) NOT NULL,
  `password` varchar(50) NOT NULL,
  `code` varchar(20) NOT NULL,
  `active` int(1) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1; 

Koneksi Database
Buka folder application / config / database.php
 $db['default'] = array(
 'dsn' => '',
 'hostname' => 'localhost',
 'username' => 'root',
 'password' => '',
 'database' => 'codeigniter',
 'dbdriver' => 'mysqli',
 'dbprefix' => '',
 'pconnect' => FALSE,
 'db_debug' => (ENVIRONMENT !== 'production'),
 'cache_on' => FALSE,
 'cachedir' => '',
 'char_set' => 'utf8',
 'dbcollat' => 'utf8_general_ci',
 'swap_pre' => '',
 'encrypt' => FALSE,
 'compress' => FALSE,
 'stricton' => FALSE,
 'failover' => array(),
 'save_queries' => TRUE
); 

Buat Model
Buka folder application / models kemudian buat file dengan nama Users_model.php
 <?php
defined('BASEPATH') OR exit('No direct script access allowed');

class Users_model extends CI_Model {

 function __construct(){
  parent::__construct();
  $this->load->database();
 }

 public function getAllUsers(){
  $query = $this->db->get('users');
  return $query->result(); 
 }

 public function insert($user){
  $this->db->insert('users', $user);
  return $this->db->insert_id(); 
 }

 public function getUser($id){
  $query = $this->db->get_where('users',array('id'=>$id));
  return $query->row_array();
 }

 public function activate($data, $id){
  $this->db->where('users.id', $id);
  return $this->db->update('users', $data);
 }

}
 

Buat controller
Buka folder application / controllers kemudian buat file User.php
 <?php
defined('BASEPATH') OR exit('No direct script access allowed');

class User extends CI_Controller {

 function __construct(){
  parent::__construct();
  $this->load->model('users_model');
  $this->load->helper(array('form', 'url'));
  $this->load->library('form_validation');
  $this->load->library('session');

        //get all users
  $this->data['users'] = $this->users_model->getAllUsers();
 }

 public function index(){
  $this->load->view('register', $this->data);
 }

 public function register(){
  $this->form_validation->set_rules('email', 'Email', 'valid_email|required');
  $this->form_validation->set_rules('password', 'Password', 'required|min_length[7]|max_length[30]');
  $this->form_validation->set_rules('password_confirm', 'Confirm Password', 'required|matches[password]');

  if ($this->form_validation->run() == FALSE) { 
   $this->load->view('register', $this->data);
  }
  else{
   //get user inputs
   $email = $this->input->post('email');
   $password = $this->input->post('password');

   //generate simple random code
   $set = '123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
   $code = substr(str_shuffle($set), 0, 12);

   //insert user to users table and get id
   $user['email'] = $email;
   $user['password'] = $password;
   $user['code'] = $code;
   $user['active'] = false;
   $id = $this->users_model->insert($user);

   //set up email
   $config = array(
    'protocol' => 'smtp',
      'smtp_host' => 'ssl:HOST SMTP', //Ubah sesuai dengan host anda
      'smtp_port' => 465,
      'smtp_user' => 'YOUR EMAIL HOST', // Ubah sesuai dengan email yang dipakai untuk mengirim konfirmasi
      'smtp_pass' => 'EMAIL HOST', // ubah dengan password host anda
      'smtp_username' => 'USERNAME SMTP', // Masukkan username SMTP anda
      'mailtype' => 'html',
      'charset' => 'iso-8859-1',
      'wordwrap' => TRUE
     );

   $message =  "
   <html>
   <head>
   <title>Verification Code</title>
   </head>
   <body>
   <h2>Thank you for Registering.</h2>
   <p>Your Account:</p>
   <p>Email: ".$email."</p>
   <p>Password: ".$password."</p>
   <p>Please click the link below to activate your account.</p>
   <h4><a href='".base_url()."user/activate/".$id."/".$code."'>Activate My Account</a></h4>
   </body>
   </html>
   ";
   
   $this->load->library('email', $config);
   $this->email->set_newline("\r\n");
   $this->email->from($config['smtp_user']);
   $this->email->to($email);
   $this->email->subject('Signup Verification Email');
   $this->email->message($message);

      //sending email
   if($this->email->send()){
    $this->session->set_flashdata('message','Activation code sent to email');
   }
   else{
    $this->session->set_flashdata('message', $this->email->print_debugger());
    
   }

   redirect('register');
  }

 }

 public function activate(){
  $id =  $this->uri->segment(3);
  $code = $this->uri->segment(4);

  //fetch user details
  $user = $this->users_model->getUser($id);

  //if code matches
  if($user['code'] == $code){
   //update user active status
   $data['active'] = true;
   $query = $this->users_model->activate($data, $id);

   if($query){
    $this->session->set_flashdata('message', 'User activated successfully');
   }
   else{
    $this->session->set_flashdata('message', 'Something went wrong in activating account');
   }
  }
  else{
   $this->session->set_flashdata('message', 'Cannot activate account. Code didnt match');
  }

  redirect('register');

 }

}
 

Buat Views
Berikutnya adalah membuat form sebagai tampilan, bukan folder application / views kemudian buat file dengan nama register.php
 <!DOCTYPE html>
<html>
<head>
 <meta charset="utf-8">
 <title>CodeIgniter Signup with Email Verification</title>
 <link rel="stylesheet" type="text/css" href="<?php echo base_url(); ?>bootstrap/css/bootstrap.min.css">
</head>
<body>
<nav class="navbar navbar-default navbar-static-top">
  <div class="container-fluid">
   <div class="navbar-header">
    <a class="navbar-brand" href="https://www.tutorialswb.com/">TutorialsWB</a>
    <ul class="nav navbar-nav">
     <li class="active"><a href="#">CodeIgniter Signup with Email Verification</a></li>
    </ul>
   </div>
  </div>
 </nav>
<div class="container">
 <div class="row">
  <div class="col-sm-4">
   <?php
       if(validation_errors()){
        ?>
        <div class="alert alert-info text-center">
         <?php echo validation_errors(); ?>
        </div>
        <?php
       }
 
    if($this->session->flashdata('message')){
     ?>
     <div class="alert alert-info text-center">
      <?php echo $this->session->flashdata('message'); ?>
     </div>
     <?php
    } 
      ?>
   <h3 class="text-center">Signup Form</h3>
   <form method="POST" action="<?php echo base_url().'user/register'; ?>">
    <div class="form-group">
     <label for="email">Email:</label>
     <input type="text" class="form-control" id="email" name="email" value="<?php echo set_value('email'); ?>">
    </div>
    <div class="form-group">
     <label for="password">Password:</label>
     <input type="password" class="form-control" id="password" name="password" value="<?php echo set_value('password'); ?>">
    </div>
    <div class="form-group">
     <label for="password_confirm">Password:</label>
     <input type="password" class="form-control" id="password_confirm" name="password_confirm" value="<?php echo set_value('password_confirm'); ?>">
    </div>
    <button type="submit" class="btn btn-primary">Register</button>
   </form>
  </div>
  <div class="col-sm-8">
   <h3 class="text-center">Users Table</h3>
   <table class="table table-bordered table-striped">
    <thead>
     <tr>
      <th>UserID</th>
      <th>Email</th>
      <th>Password</th>
      <th>Code</th>
      <th>Active</th>
     </tr>
    </thead>
    <tbody>
    <?php
     foreach($users as $row){
      ?>
      <tr>
       <td><?php echo $row->id; ?></td>
       <td><?php echo $row->email; ?></td>
       <td><?php echo $row->password; ?></td>
       <td><?php echo $row->code; ?></td>
       <td><?php echo $row->active ? 'True' : 'False'; ?></td>
      </tr>
      <?php
     }
    ?>
    </tbody>
   </table>
  </div>
 </div>
</div>
</body>
</html> 

Kalian bisa melihat demo dan mendownload aplikasinya dibawah ini, kalian bisa mempelajari dan memodifikasi sesuai dengan yang anda inginkan

DEMO     DOWNLOAD 

Semoga apa yang kami share ini bermanfaat bagi anda, jika kalian tidak begitu memahami silahkan tinggalkan komentar dibawah.


SUBSCRIBE TO OUR NEWSLETTER

close