How to create a contact form with CodeIgniter?

Introduction

The following has been tested on a Cloud9 server with the following versions:

Here is a screenshot of the result:

Contact form page with CodeIgniter

Step 1: routes

Add the following route in the file /application/config/routes.php:

/application/config/routes.php
$route['contact'] = 'contact/index';

Step 2: views

Templates

Create two templates (header.php and footer.php) in /application/views/templates:

<?php
//application/views/templates/header.php
?>

<!DOCTYPE html>
<html lang="fr">
    <head>

        <!-- Specify UTF-8 encoding -->
        <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
        <!-- Viewport for Bootstrap -->
        <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
        <!-- Bootstrap CSS -->
        <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css" integrity="sha384-MCw98/SFnGE8fJT3GXwEOngsV7Zt27NXFoaoApmYm81iuXoPkFOJwJ8ERdknLPMO" crossorigin="anonymous">
        <!-- Style sheet -->
        <link rel="stylesheet" type="text/css" href="/css/generic.css">
        <link rel="stylesheet" type="text/css" href="/css/wh-min-max.css">
        <link rel="stylesheet" type="text/css" href="/css/bg-colors.css"> 
        <!-- Font awesome -->
        <link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.3.1/css/all.css" integrity="sha384-mzrmE5qonljUremFsqc01SB46JvROS7bZs3IO2EmfFsd15uHvIt+Y8vEf7N7fWAU" crossorigin="anonymous">
        <!-- Google fonts -->
        <link href="https://fonts.googleapis.com/css?family=Bai+Jamjuree" rel="stylesheet">

        <!-- Page title and description -->
        <title><?= $headerTitle ?></title>
        <meta name="description" content="<?= $headerDescription ?>"> 

    </head>
    <body>

        <div class="hmin-100-vh mt-1 mb-5">
            <div id="page-body" class="text-justify wmax-1200-px mx-auto my-0 py-0 px-md-0 px-2">

<!-- :::::::::::::::::::::::::::::::: TITLE :::::::::::::::::::::::::::::::: -->

                <?php if (isset($title)) { ?>
                <h1><?= $title; ?></h1>
                <?php } ?>

The following template is the footer of the page:

<?php
//application/views/templates/footer.php
?>

            </div>  <!-- end of max width -->
        </div>  <!-- end of height 100% -->

<!-- ::::::::::::::::::::::::::::: JAVASCRIPT :::::::::::::::::::::::::::::: -->

        <!-- Optional JavaScript -->
        <!-- jQuery first, then Popper.js, then Bootstrap JS -->
        <script src="https://code.jquery.com/jquery-3.3.1.slim.min.js" integrity="sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo" crossorigin="anonymous"></script>
        <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.3/umd/popper.min.js" integrity="sha384-ZMP7rVo3mIykV+2+9J3UJ46jBk0WLaUAdn689aCwoqbBJiSnjAK/l8WvCWPIPm49" crossorigin="anonymous"></script>
        <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/js/bootstrap.min.js" integrity="sha384-ChfqqxuZUCnJSK3+MXmPNIyE6ZbWh2IMqE241rYiqJxyMiZ6OW/JmZQ5stwEULTy" crossorigin="anonymous"></script>
    </body>
</html>

The following template (in /application/views/templates/alert.php) is used on each page to display errors and flash messages.

<?php
//application/views/templates/alert.php
?>
<?php 
    if (validation_errors()) { ?>
    <div class="alert alert-danger alert-dismissible fade show my-3" role="alert">
        <button type="button" class="close" data-dismiss="alert" aria-label="Close">
            <span aria-hidden="true">&times;</span>
        </button>
        <?= validation_errors() ?>
    </div>
<?php } 

// ---------------------------------- SUCCESS ----------------------------------

if($this->session->flashdata('msg-success'))
{ 
?>
    <div class="alert alert-success alert-dismissible fade show my-3" role="alert">
        <button type="button" class="close" data-dismiss="alert" aria-label="Close">
            <span aria-hidden="true">&times;</span>
        </button>
        <i class="fa fa-check-circle  text-success mr2 fa-lg"></i>
        <?= $this->session->flashdata('msg-success') ?>
    </div>
<?php } 

// ---------------------------------- DANGER -----------------------------------

if($this->session->flashdata('msg-danger')){ ?>
    <div class="alert alert-danger alert-dismissible fade show my-3" role="alert">
        <button type="button" class="close" data-dismiss="alert" aria-label="Close">
            <span aria-hidden="true">&times;</span>
        </button>
        <i class="fa fa-times-circle text-danger mr2 fa-lg" aria-hidden="true"></i>
        <?= $this->session->flashdata('msg-danger') ?>
    </div>
<?php } ?>

Contact form

Create the page content (index.php) that will contain the contact form in /application/views/contact/

<?php 
//application/views/contact/index.php
?>

    <?= form_open('contact'); ?>

        <div class="form-group">
            <label for="ID_email" class="text-left">E-mail</label>
            <input name="email" required type="email" class="form-control" id="ID_email" placeholder="Enter your email here" value="<?= set_value('email'); ?>">
        </div>

        <div class="form-group">
            <label for="ID_email" class="text-left">Title</label>
            <input name="title" required type="text" class="form-control" id="ID_email" placeholder="Message title" value="<?= set_value('title'); ?>">
        </div>

        <div class="form-group">
            <label for="ID_message">Message</label>
            <textarea name="message" required class="form-control" id="ID_message" rows="16" placeholder="Your message ici"><?= set_value('message'); ?></textarea>
            <small class="form-text text-muted">Un doute ? Vérifier la conjugaison d'un verbe sur <a href="https://www.conjugatix.com" target="_blank">Conjugatix.com</a> !</small>
        </div>

        <div class="text-right">
            <button class="btn btn-primary">Envoyer</button>
        </div>

    </form>

Step 3: Controller

Create a new file Contact.php in /application/controllers and add the following controller in the file. This controller check if the form data are valid. If not, it displays the form. When form data are valid, the message is sent via the Contact model.

<?php
//application/controllers/Contact.php

// Contact controller
// This controller is used to manage the contact form page
class Contact extends CI_Controller
{

    // Constructor, load the model
    public function __construct() 
    {
        parent::__construct();
        // Load contact model
        $this->load->model('contact_model');
    }

    // Main controller for the contact form
    public function index()
    {
        // Load form libraries
        $this->load->helper('form');
        $this->load->library('form_validation');
        $this->load->helper('url');

        // Check if data are provided
        $this->form_validation->set_rules('email', 'e-mail', 'trim|required' , array('required' => "Valid email required") );
        $this->form_validation->set_rules('title', 'Titre', 'trim|required', array('required' => "Tile required") );
        $this->form_validation->set_rules('message', 'message', 'trim|required', array('required' => "Message required") );

        if ($this->form_validation->run() === FALSE)
        {
            // Form is not valid, display the form once again
            $this->displayForm();
        }
        else
        {
            // Form is valid, send the message
            $this->contact_model->sendMessage();
            redirect('/');
        }
    }

    // Display the contact form
    private function displayForm()
    {
        // Prepare data to the controler
        $data['headerTitle'] = 'Contact';
        $data['headerDescription'] = 'Page de contact';
        $data['title'] = 'Contact';

        // Display page
        $this->load->view('templates/header', $data);
        $this->load->view('templates/alert', $data);
        $this->load->view('contact/index', $data);
        $this->load->view('templates/footer', $data);
    }

}

Step 4: Model

The following model is used to send the message, customize address and email configuration. This example assume that the main e-mail parameters has been set at the application level. See (Email configuration while installing).

<?php
class Contact_model extends CI_Model {

    // Constructor of the model, load the email library
    public function __construct()
    {
        // Load email library
        $this->load->library('email'); 
    }

    // Prepare and send the message
    public function sendMessage()
    {
        // Set email parameters (sender, recipients ...)
        $this->email->from('user@server.name', 'Human readable name');
        $this->email->reply_to($this->input->post('email'));
        $this->email->to('recipient@example.com','Human readable recipient name');
        $this->email->subject('[My site contact] '.$this->input->post('title'));

        // Prepare data to be inserted in template
        $data=array(    'email'     => $this->input->post('email'),
                        'message'   => $this->input->post('message')
                    );

        // Load an email template view
        $message = $this->load->view('emails/contact', $data, TRUE);
        $this->email->message($message);

        // Send the e-mail and manage errors
        try
        {
            $ret = $this->email->send();
            if ($ret)
                $this->session->set_flashdata('msg-success', 'Your message has been sent.');
            else
                $this->session->set_flashdata('msg-danger', "Something wrong happened while sending your message.");
        }
        catch(Exception $e)
        {
            $this->session->set_flashdata('msg-danger', "Something wrong happened whil sending your message (".$e->getMessage().")");
        }
    }
}

See also


Last update : 10/04/2018