Create Contact Form in CodeIgniter with Email

Contact Form is a must-have component for every web application. It’s a simple and quick way to communicate with the website owner. Through the Contact Us form the website’s visitor can submit their questions, feedback, and suggestions to the site administrator. In the same way, contact us form is very useful for the site owner to get the service requests or customer queries directly from the website.

In most cases, the submitted contact request is sent to the site admin via email. So, the site admin of the respective organization can get the request instantly and send a quick response to the sender. Also, the response can send automatically to the request sender from the script. In this tutorial, we will show you how to create a simple contact form in CodeIgniter framework and send email after the form submission. The example code helps you to build CodeIgniter contact us form with validation and email sending functionality.

Controller (Contact.php)

The Contact controller handles the contact form submission process, it has 3 functions, __construct(), index(), and sendEmail().
__construct() – Loads the Form Validation library.

index()

  • If the contact form is submitted:
    • Validate form fields using CodeIgniter Form Validation library.
    • Pass form data in sendEmail() function to send contact request email.
    • Store the status message in an Array.
  • Pass the POST data and form submission status to the view.

sendEmail()

  • Send HTML email with the contact form data using Email library in CodeIgniter.
  • Return true on success or false on failure.
<?php defined('BASEPATH') OR exit('No direct script access allowed');

class 
Contact extends CI_Controller {
    
    function 
__construct() {
        
parent::__construct();
        
        
// Load form validation library
        
$this->load->library('form_validation');
    }
    
    public function 
index(){
        
$data $formData = array();
        
        
// If contact request is submitted
        
if($this->input->post('contactSubmit')){
            
            
// Get the form data
            
$formData $this->input->post();
            
            
// Form field validation rules
            
$this->form_validation->set_rules('name''Name''required');
            
$this->form_validation->set_rules('email''Email''required|valid_email');
            
$this->form_validation->set_rules('subject''Subject''required');
            
$this->form_validation->set_rules('message''Message''required');
            
            
// Validate submitted form data
            
if($this->form_validation->run() == true){
                
                
// Define email data
                
$mailData = array(
                    
'name' => $formData['name'],
                    
'email' => $formData['email'],
                    
'subject' => $formData['subject'],
                    
'message' => $formData['message']
                );
                
                
// Send an email to the site admin
                
$send $this->sendEmail($mailData);
                
                
// Check email sending status
                
if($send){
                    
// Unset form data
                    
$formData = array();
                    
                    
$data['status'] = array(
                        
'type' => 'success',
                        
'msg' => 'Your contact request has been submitted successfully.'
                    
);
                }else{
                    
$data['status'] = array(
                        
'type' => 'error',
                        
'msg' => 'Some problems occured, please try again.'
                    
);
                }
            }
        }
        
        
// Pass POST data to view
        
$data['postData'] = $formData;
        
        
// Pass the data to view
        
$this->load->view('contact/index'$data);
    }
    
    private function 
sendEmail($mailData){
        
// Load the email library
        
$this->load->library('email');
        
        
// Mail config
        
$to 'recipient@gmail.com';
        
$from 'codexworld@gmail.com';
        
$fromName 'CodexWorld';
        
$mailSubject 'Contact Request Submitted by '.$mailData['name'];
        
        
// Mail content
        
$mailContent '
            <h2>Contact Request Submitted</h2>
            <p><b>Name: </b>'
.$mailData['name'].'</p>
            <p><b>Email: </b>'
.$mailData['email'].'</p>
            <p><b>Subject: </b>'
.$mailData['subject'].'</p>
            <p><b>Message: </b>'
.$mailData['message'].'</p>
        '
;
            
        
$config['mailtype'] = 'html';
        
$this->email->initialize($config);
        
$this->email->to($to);
        
$this->email->from($from$fromName);
        
$this->email->subject($mailSubject);
        
$this->email->message($mailContent);
        
        
// Send email & return status
        
return $this->email->send()?true:false;
    }
    
}

View (contact/index.php)

This file contains contact form HTML that allows the user to submit a contact request.

  • Initially, a form is displayed with some basic fields (Name, Email, Subject, and Message).
  • On submission, the form is submitted to the index() method of the Contact controller.
  • If form validation error occurs, the message is shown under the input field.
  • If form submission is submitted, an email is sent to the site admin and the success message is shown to the user.
<div class="content-frm">
    <!-- Display the status message -->
    <?php if(!empty($status)){ ?>
    <div class="status <?php echo $status['type']; ?>"><?php echo $status['msg']; ?></div>
    <?php ?>
    
    <!-- Contact form -->
    <form action="" method="post">
        <div class="form-cw">
            <h2>Contact Us</h2>
            <button type="submit" name="contactSubmit" class="frm-submit" value="Submit">
                <img src="<?php echo base_url('assets/images/mail.png'); ?>">
            </button>
            <div class="clear"></div>
        </div>
        
        <div class="input-group">
            <input type="text" name="name" value="<?php echo !empty($postData['name'])?$postData['name']:''?>" placeholder="NAME">
            <?php echo form_error('name','<p class="field-error">','</p>'); ?>
        </div>
        
        <div class="input-group">
            <input type="email" name="email" value="<?php echo !empty($postData['email'])?$postData['email']:''?>" placeholder="EMAIL@ADDRESS.COM">
            <?php echo form_error('email','<p class="field-error">','</p>'); ?>
        </div>
        
        <div class="input-group">
            <input type="text" name="subject" value="<?php echo !empty($postData['subject'])?$postData['subject']:''?>" placeholder="SUBJECT">
            <?php echo form_error('subject','<p class="field-error">','</p>'); ?>
        </div>
        
        <div class="input-group">
            <textarea name="message" placeholder="YOUR MESSAGE"><?php echo !empty($postData['message'])?$postData['message']:''?></textarea>
            <?php echo form_error('message','<p class="field-error">','</p>'); ?>
        </div>
        
        <input type="submit" name="contactSubmit" class="frm-submit" value="Submit">
    </form>
</div>

Creating a Simple Contact Form with PHP

Conclusion

Here we have tried to provide the quickest way to integrate contact form in CodeIgniter application. The contact form functionality can be easily extended as per your needs. The form validation and email sending functionality already implemented in the example code. You can integrate the CAPTCHA functionality in CodeIgniter to protect the form from spam submission.

Do you want to get implementation help, or enhance the functionality of this script? Click here to Submit Service Request

4 Comments

  1. Padma Said...
  2. Ritesh Kumar Singh Said...
  3. Daryl Snowden Said...

Leave a reply

keyboard_double_arrow_up