Creating a CodeIgniter Signup From with Email Verification

This tutorial tackles how to create a simple signup form with validation and email verification in CodeIgniter. CodeIgniter is a lightweight PHP framework that uses MVC(Model-View-Controller) architecture. Sending email verification is a way to check whether the users' inputted email is valid or not.

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 the 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.

Or you can create the database programmatically by creating a new database naming codeigniter. After that, go to the SQL tab in your PHPMyAdmin and Copy/Paste the code below. Then, click the Go button.

  1. CREATE TABLE `users` (
  2. `email` varchar(100) NOT NULL,
  3. `password` varchar(50) NOT NULL,
  4. `code` varchar(20) NOT NULL,
  5. `active` int(1) NOT NULL

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 on 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'] = 'http://localhost/codeigniter_register_email/';

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 a 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

The 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. <?php
  3. defined('BASEPATH') OR exit('No direct script access allowed');
  4.  
  5. class User extends CI_Controller {
  6.  
  7. function __construct(){
  8. parent::__construct();
  9. $this->load->model('users_model');
  10. $this->load->helper(array('form', 'url'));
  11. $this->load->library('form_validation');
  12. $this->load->library('session');
  13.  
  14. //get all users
  15. $this->data['users'] = $this->users_model->getAllUsers();
  16. }
  17.  
  18. public function index(){
  19. $this->load->view('register', $this->data);
  20. }
  21.  
  22. public function register(){
  23. $this->form_validation->set_rules('email', 'Email', 'valid_email|required');
  24. $this->form_validation->set_rules('password', 'Password', 'required|min_length[7]|max_length[30]');
  25. $this->form_validation->set_rules('password_confirm', 'Confirm Password', 'required|matches[password]');
  26.  
  27. if ($this->form_validation->run() == FALSE) {
  28. $this->load->view('register', $this->data);
  29. }
  30. else{
  31. //get user inputs
  32. $email = $this->input->post('email');
  33. $password = $this->input->post('password');
  34.  
  35. //generate simple random code
  36. $set = '123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
  37. $code = substr(str_shuffle($set), 0, 12);
  38.  
  39. //insert user to users table and get id
  40. $user['email'] = $email;
  41. $user['password'] = $password;
  42. $user['code'] = $code;
  43. $user['active'] = false;
  44. $id = $this->users_model->insert($user);
  45.  
  46. //set up email
  47. $config = array(
  48. 'protocol' => 'mail',
  49. 'smtp_host' => 'smtp.gmail.com',
  50. 'smtp_port' => 465,
  51. 'smtp_user' => '[email protected]', // change it to yours
  52. 'smtp_pass' => 'sourcecodester', // change it to yours
  53. 'mailtype' => 'html',
  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 used Bootstrap in the views. You may download bootstrap using this link.

Create the ff files inside the 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. unset($_SESSION['message']);
  29. }
  30. ?>
  31. <h3 class="text-center">Signup Form</h3>
  32. <form method="POST" action="<?php echo base_url().'user/register'; ?>">
  33. <div class="form-group">
  34. <label for="email">Email:</label>
  35. <input type="text" class="form-control" id="email" name="email" value="<?php echo set_value('email'); ?>">
  36. </div>
  37. <div class="form-group">
  38. <label for="password">Password:</label>
  39. <input type="password" class="form-control" id="password" name="password" value="<?php echo set_value('password'); ?>">
  40. </div>
  41. <div class="form-group">
  42. <label for="password_confirm">Confirm Password:</label>
  43. <input type="password" class="form-control" id="password_confirm" name="password_confirm" value="<?php echo set_value('password_confirm'); ?>">
  44. </div>
  45. <button type="submit" class="btn btn-primary">Register</button>
  46. </form>
  47. </div>
  48. <div class="col-sm-8">
  49. <h3 class="text-center">Users Table</h3>
  50. <table class="table table-bordered table-striped">
  51. <thead>
  52. <tr>
  53. <th>UserID</th>
  54. <th>Email</th>
  55. <th>Password</th>
  56. <th>Code</th>
  57. <th>Active</th>
  58. </tr>
  59. </thead>
  60. <tbody>
  61. <?php
  62. foreach($users as $row){
  63. ?>
  64. <tr>
  65. <td><?php echo $row->id; ?></td>
  66. <td><?php echo $row->email; ?></td>
  67. <td><?php echo $row->password; ?></td>
  68. <td><?php echo $row->code; ?></td>
  69. <td><?php echo $row->active ? 'True' : 'False'; ?></td>
  70. </tr>
  71. <?php
  72. }
  73. ?>
  74. </tbody>
  75. </table>
  76. </div>
  77. </div>
  78. </div>
  79. </body>
  80. </html>

Demo

That ends this tutorial. Test your work if it is working. You can also download my working sample source code that I have made for this tutorial. The download button is located below.

Explore on this website for more tutorials and free source code.

Happy Coding :)

Comments

Submitted byPrarthana A Ch… (not verified)on Wed, 04/13/2022 - 19:50

I am unable to get the email verification message and the email Getting error saying : Unable to send email using PHP SMTP. Your server might not be configured to send mail using this method. Please help out !

Add new comment