CodeIgniter Signup with Email Verification

Submitted by: 
Language: 
Visitors have accessed this post 8814 times.

Installing CodeIgniter

If you don't have CodeIgniter installed yet, you can use this link to download the latest version of CodeIgniter which is 3.1.7 that I've used in this source code.

After downloading, extract the file in the folder of your server. Since I'm using XAMPP as my localhost server, I've put the folder in htdocs folder of my XAMPP.

Then, you can test whether you have successfully installed codeigniter by typing your app name in your browser. In my case, I named my app as codeigniter_register_email so I'm using the below code.

  1. localhost/codeigniter_register_email

codeigniter successful install

Removing index.php in our URLs

By default, index.php is included in every URL of our app. To remove this, please refer to my tutorial How to Remove Index.Php in the URL of Codeigniter Application.

Creating our Database

I've included a .sql file located in db folder in the downloadable of this tutorial. All you need to do is import the file into your phpMyAdmin. If you have no idea how to import, please refer to my tutorial How import .sql file to restore MySQL database.

You should be able to add a database named codeigniter.

Connecting our App into our Database

Next, we're going to connect our codeigniter application to the database that we created earlier.

1. In your codeigniter app folder, open database.php located in application/config folder.

2. Update database.php with your credential the same as what I did below.

  1. $db['default'] = array(
  2. 'dsn' => '',
  3. 'hostname' => 'localhost',
  4. 'username' => 'root',
  5. 'password' => '',
  6. 'database' => 'codeigniter',
  7. 'dbdriver' => 'mysqli',
  8. 'dbprefix' => '',
  9. 'pconnect' => FALSE,
  10. 'db_debug' => (ENVIRONMENT !== 'production'),
  11. 'cache_on' => FALSE,
  12. 'cachedir' => '',
  13. 'char_set' => 'utf8',
  14. 'dbcollat' => 'utf8_general_ci',
  15. 'swap_pre' => '',
  16. 'encrypt' => FALSE,
  17. 'compress' => FALSE,
  18. 'stricton' => FALSE,
  19. 'failover' => array(),
  20. 'save_queries' => TRUE
  21. );

Configuring our App

Next, we configure our base url and remove index.php in our index page.

1. In your codeigniter app folder, open config.php located in application/config folder.
2. Find and edit the ff lines:

  1. $config['index_page'] = '';
  2. $config['base_url'] = '<a href="http://localhost/codeigniter_register_email/';

" rel="nofollow">http://localhost/codeigniter_register_email/';
[/geshifilter-php]

Defining our Routes

Next, we define our routes by naming our default controller and the route for our register.

Open routes.php located in application/config folder and update or add the ff lines.

  1. $route['default_controller'] = 'user';
  2. $route['register'] = 'user';

Creating our Model

Next, we create the model for our app. Take note that the first letter of your model name should be in CAPITAL letter and the name of the model should be the same as the file name to avoid confusion.

Create a file named Users_model.php in application/models folder of our app and put the ff codes:

  1. <?php
  2. defined('BASEPATH') OR exit('No direct script access allowed');
  3.  
  4. class Users_model extends CI_Model {
  5.  
  6. function __construct(){
  7. parent::__construct();
  8. $this->load->database();
  9. }
  10.  
  11. public function getAllUsers(){
  12. $query = $this->db->get('users');
  13. return $query->result();
  14. }
  15.  
  16. public function insert($user){
  17. $this->db->insert('users', $user);
  18. return $this->db->insert_id();
  19. }
  20.  
  21. public function getUser($id){
  22. $query = $this->db->get_where('users',array('id'=>$id));
  23. return $query->row_array();
  24. }
  25.  
  26. public function activate($data, $id){
  27. $this->db->where('users.id', $id);
  28. return $this->db->update('users', $data);
  29. }
  30.  
  31. }

Creating our Controller

Next step is to create our controller. Controllers follow the same naming convention as models.

Create a file named User.php in application/controllers folder of our app and put the ff codes.

  1. <?php
  2. defined('BASEPATH') OR exit('No direct script access allowed');
  3.  
  4. class User extends CI_Controller {
  5.  
  6. function __construct(){
  7. parent::__construct();
  8. $this->load->model('users_model');
  9. $this->load->helper(array('form', 'url'));
  10. $this->load->library('form_validation');
  11. $this->load->library('session');
  12.  
  13. //get all users
  14. $this->data['users'] = $this->users_model->getAllUsers();
  15. }
  16.  
  17. public function index(){
  18. $this->load->view('register', $this->data);
  19. }
  20.  
  21. public function register(){
  22. $this->form_validation->set_rules('email', 'Email', 'valid_email|required');
  23. $this->form_validation->set_rules('password', 'Password', 'required|min_length[7]|max_length[30]');
  24. $this->form_validation->set_rules('password_confirm', 'Confirm Password', 'required|matches[password]');
  25.  
  26. if ($this->form_validation->run() == FALSE) {
  27. $this->load->view('register', $this->data);
  28. }
  29. else{
  30. //get user inputs
  31. $email = $this->input->post('email');
  32. $password = $this->input->post('password');
  33.  
  34. //generate simple random code
  35. $set = '123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
  36. $code = substr(str_shuffle($set), 0, 12);
  37.  
  38. //insert user to users table and get id
  39. $user['email'] = $email;
  40. $user['password'] = $password;
  41. $user['code'] = $code;
  42. $user['active'] = false;
  43. $id = $this->users_model->insert($user);
  44.  
  45. //set up email
  46. $config = array(
  47. 'protocol' => 'smtp',
  48. 'smtp_host' => 'ssl://smtp.googlemail.com',
  49. 'smtp_port' => 465,
  50. 'smtp_user' => '<a href="mailto:[email protected]" rel="nofollow">[email protected]</a>', // change it to yours
  51. 'smtp_pass' => 'mysourcepass', // change it to yours
  52. 'mailtype' => 'html',
  53. 'charset' => 'iso-8859-1',
  54. 'wordwrap' => TRUE
  55. );
  56.  
  57. $message = "
  58. <html>
  59. <head>
  60. <title>Verification Code</title>
  61. </head>
  62. <body>
  63. <h2>Thank you for Registering.</h2>
  64. <p>Your Account:</p>
  65. <p>Email: ".$email."</p>
  66. <p>Password: ".$password."</p>
  67. <p>Please click the link below to activate your account.</p>
  68. <h4><a href='".base_url()."user/activate/".$id."/".$code."'>Activate My Account</a></h4>
  69. </body>
  70. </html>
  71. ";
  72.  
  73. $this->load->library('email', $config);
  74. $this->email->set_newline("\r\n");
  75. $this->email->from($config['smtp_user']);
  76. $this->email->to($email);
  77. $this->email->subject('Signup Verification Email');
  78. $this->email->message($message);
  79.  
  80. //sending email
  81. if($this->email->send()){
  82. $this->session->set_flashdata('message','Activation code sent to email');
  83. }
  84. else{
  85. $this->session->set_flashdata('message', $this->email->print_debugger());
  86.  
  87. }
  88.  
  89. redirect('register');
  90. }
  91.  
  92. }
  93.  
  94. public function activate(){
  95. $id = $this->uri->segment(3);
  96. $code = $this->uri->segment(4);
  97.  
  98. //fetch user details
  99. $user = $this->users_model->getUser($id);
  100.  
  101. //if code matches
  102. if($user['code'] == $code){
  103. //update user active status
  104. $data['active'] = true;
  105. $query = $this->users_model->activate($data, $id);
  106.  
  107. if($query){
  108. $this->session->set_flashdata('message', 'User activated successfully');
  109. }
  110. else{
  111. $this->session->set_flashdata('message', 'Something went wrong in activating account');
  112. }
  113. }
  114. else{
  115. $this->session->set_flashdata('message', 'Cannot activate account. Code didnt match');
  116. }
  117.  
  118. redirect('register');
  119.  
  120. }
  121.  
  122. }

Creating our Register Form

Lastly, we create the register form of our app. Take note that I've use Bootstrap in the views. You may download bootstrap using this link.

Create the ff files inside application/views folder.

register.php

  1. <!DOCTYPE html>
  2. <html>
  3. <head>
  4. <meta charset="utf-8">
  5. <title>CodeIgniter Signup with Email Verification</title>
  6. <link rel="stylesheet" type="text/css" href="<?php echo base_url(); ?>bootstrap/css/bootstrap.min.css">
  7. </head>
  8. <body>
  9. <div class="container">
  10. <h1 class="page-header text-center">CodeIgniter Signup with Email Verification</h1>
  11. <div class="row">
  12. <div class="col-sm-4">
  13. <?php
  14. if(validation_errors()){
  15. ?>
  16. <div class="alert alert-info text-center">
  17. <?php echo validation_errors(); ?>
  18. </div>
  19. <?php
  20. }
  21.  
  22. if($this->session->flashdata('message')){
  23. ?>
  24. <div class="alert alert-info text-center">
  25. <?php echo $this->session->flashdata('message'); ?>
  26. </div>
  27. <?php
  28. }
  29. ?>
  30. <h3 class="text-center">Signup Form</h3>
  31. <form method="POST" action="<?php echo base_url().'user/register'; ?>">
  32. <div class="form-group">
  33. <label for="email">Email:</label>
  34. <input type="text" class="form-control" id="email" name="email" value="<?php echo set_value('email'); ?>">
  35. </div>
  36. <div class="form-group">
  37. <label for="password">Password:</label>
  38. <input type="password" class="form-control" id="password" name="password" value="<?php echo set_value('password'); ?>">
  39. </div>
  40. <div class="form-group">
  41. <label for="password_confirm">Password:</label>
  42. <input type="password" class="form-control" id="password_confirm" name="password_confirm" value="<?php echo set_value('password_confirm'); ?>">
  43. </div>
  44. <button type="submit" class="btn btn-primary">Register</button>
  45. </form>
  46. </div>
  47. <div class="col-sm-8">
  48. <h3 class="text-center">Users Table</h3>
  49. <table class="table table-bordered table-striped">
  50. <thead>
  51. <tr>
  52. <th>UserID</th>
  53. <th>Email</th>
  54. <th>Password</th>
  55. <th>Code</th>
  56. <th>Active</th>
  57. </tr>
  58. </thead>
  59. <tbody>
  60. <?php
  61. foreach($users as $row){
  62. ?>
  63. <tr>
  64. <td><?php echo $row->id; ?></td>
  65. <td><?php echo $row->email; ?></td>
  66. <td><?php echo $row->password; ?></td>
  67. <td><?php echo $row->code; ?></td>
  68. <td><?php echo $row->active ? 'True' : 'False'; ?></td>
  69. </tr>
  70. <?php
  71. }
  72. ?>
  73. </tbody>
  74. </table>
  75. </div>
  76. </div>
  77. </div>
  78. </body>
  79. </html>

That ends this tutorial. Happy Coding :)


Add new comment

Filtered HTML

  • Web page addresses and e-mail addresses turn into links automatically.
  • You may insert videos with [video:URL]
  • Allowed HTML tags: <a> <em> <strong> <cite> <blockquote> <code> <ul> <ol> <li> <dl> <dt> <dd> <table> <tr> <td> <th> <img> <h1> <h2> <h3> <iframe> [video]
  • You can enable syntax highlighting of source code with the following tags: <code>, <blockcode>, <asp>, <c>, <cpp>, <csharp>, <css>, <html4strict>, <java>, <javascript>, <mysql>, <php>, <python>, <sql>, <vb>, <vbnet>. The supported tag styles are: <foo>, [foo].
  • Lines and paragraphs break automatically.

Plain text

  • No HTML tags allowed.
  • Lines and paragraphs break automatically.
CAPTCHA
This question is for testing whether or not you are a human visitor and to prevent automated spam submissions.