How to create a registration form with image upload in CodeIgniter 3

CodeIgniter has a file upload library using which you can upload an image or a file to the server. If you load the upload library with some config parameters, you can just call do_upload() method to upload an image in CodeIgniter 3.

In this topic, we will create a user registration form in CodeIgniter 3 and MySQL with preview and upload image. CodeIgniter 3 form validation and image validation will be done and also it will display the photo after successful registration.

user registration form with image uplaod in Codeigniter 3

Step 1 - Create a MySQL table for user profiles

We will create a table named 'user_profile' in MySQL database. This table will store user details - name, email and photo. Table structure is given below:

Table: user_profile

How to Upload image in codeigniter

Below are the columns in this table.

  1. id - User id, primary key and auto incremented
  2. name - Name of the user
  3. email - Email of the user
  4. image - Image file of the user


CREATE TABLE `user_profile` (
  `id` int(11) NOT NULL,
  `name` varchar(255) NOT NULL,
  `email` varchar(255) NOT NULL,
  `image` varchar(500) NOT NULL

ALTER TABLE `user_profile`

ALTER TABLE `user_profile`

Folder Structure

We will be using a folder named 'ci_upload' under xampp/htdocs and keep all CodeIgniter folder/files in this folder along with our custom files. So, the root directory is xampp/htdocs/ci_upload.

We will have Controller - UploadController.php, Model - ModelUpload.php and two views (register.php and view_profile.php).

Also, we will use a folder named 'uploads' under root directory to store the uploaded images.

Step 2 - Create the views for user registration and view profile

The view for registration with a photo is simple form with name, email id and photo of the user. User can fill in name and email id and then select a photo as profile photo and submit the form. Below is the code for register.php


<!DOCTYPE html>
<html lang="en">
  <title>User Registration</title>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <link rel="stylesheet" href="">
  <link rel="stylesheet" href="<?php echo base_url('assets/css/style.css') ?>">
  <script src=""></script>
  <div class="container">
    <h4>User Registration</h4>
    <div class="msg">
      <div class="error"><?php if (isset($err_msg)) { echo $err_msg;}?></div>
      <!-- <div class="success"><?php if ($succ_msg != "") {echo $succ_msg;}?></div> -->
    <form id ="frm" action = "<?= base_url()?>register" method = "post" enctype="multipart/form-data">
      <div class="form-group col-md-12">
        <input type = "text" name="name" id = "name" class="form-control" maxlength="100" value="<?php echo set_value('name');?>" placeholder="Enter Your Name">
        <div class="error"><?php echo form_error('name'); ?></div>
      <div class="form-group col-md-12">
        <label>Email Id</label>
        <input type = "text" name="email" id = "email" class="form-control"  value="<?php echo set_value('email');?>" placeholder="Enter Your Email">
        <div class="error"><?php echo form_error('email'); ?></div>
      <div class="form-group col-md-12">
        <label for="photo">Your Photo</label>
        <div class="row">
          <div class="form-group col-md-7">
            <p class="file">
              <input type="file" name="photo" class="form-control" id="photo" onchange= "previewPhoto(this)">
              <label for="photo">Select Photo</label>
               <small color="blue">(Max size: 4MB, File type: jpg, jpeg, png, gif</small>
               <div class="error"><?php echo form_error('photo'); ?></div>
             <div class="form-group col-md-5">
              <img id="prvwPhoto">
        <div class="col-md-12 text-center">
        <input type ="submit" name="register" class="btn btn-primary" value="Submit">

When user selects a photo a JavaScript function previewPhoto() is called on onChange event of the input photo. After the form is submitted all the three input fields are validated in the Controller.

jQuery code is used to preview the photo.

Preview Photo

To Preview the photo, we will use jQuery Scripts, preview of the image is displayed using a FileReader object to read the binary data from the image. Let's see the code:

function previewPhoto(input) {
if (input.files && input.files[0]) {
    var reader = new FileReader();
    reader.onload = function (e) {
        $("#prvwPhoto").attr({'src','width':'120','height':'100','title':input.files[0].name,'alt':'Profile Photo'});

View to display user profile

After the form is submitted and processed successfully, it displays the data using another view called view_profile.php.

Upload Image in Codeigniter with database example


<!DOCTYPE html>
<html lang="en">
  <title>User Registration</title>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <link rel="stylesheet" href="">
  <link rel="stylesheet" href="<?php echo base_url('assets/css/style.css') ?>">
  <div class="container">
    <h4>User Registration Details</h4>
    <div class="msg">
      <div class="success"><?php if ($succ_msg != "") {echo $succ_msg;}?></div>
    <div class = "profile">
      $user_name = $email = $image_file = "";
      if (!empty($user)) {
        $user_name = $user->name;
        $email = $user->email;
        $image_file = $user->image;
      } ?>
      <div class="form-group col-md-12">
        <label>Name: </label> <?= $user_name;?>
      <div class="form-group col-md-12">
        <label>Email Id: </label> <?= $email;?>
      <div class="form-group col-md-12">
        <label for="photo">Photo</label>
          <img class="img-class img-circle" src="<?php echo base_url().$image_path.$image_file; ?>" />
      <div class="col-md-12 text-center">
        <a href ="<?= base_url()?>" class="btn btn-primary">Close</a>

Stylesheet is given below for all these views.


  margin-top: 20px;
  text-align: center;

    font-weight: bold;

  height: 10px;
  height: 10px;
  text-align: center;
  margin-bottom: 18px;
.file {
  position: relative;
      margin: 0;
.file label {
  background: #696969;
  padding: 12px 20px;
  color: #fff;
  font-weight: bold;
  font-size: .9em;
  transition: all .4s;
.file input {
  position: absolute;
  display: inline-block;
  left: 0;
  top: 0;
  opacity: 0.01;
  cursor: pointer;
.file input:hover + label,
.file input:focus + label {
  background: #34495E;
  color: #39D2B4;
  width: 50%;
  margin: auto;
  height: 300px;
  width: 300px;
  border-radius: 50%;
@media (max-width: 600px){
#frm {
    width: 100%;

Step 3 - Write Controller code (UploadController.php) to complete upload and registration

Our controller function will have an index() method to display the registration page and a register() method to process submitted data and upload photo.

Controller method index()

In index() method, it just loads the view that displays user registration page.

public function index(){

You can see it loads the view for user registration.

Controller Method register()

This method gets executed when user submits the form. It does the form validation and calls a model method to insert the data into "user_profile" table. Let's see the code for register() method.

public function register(){
	$element = [];
	$element['succ_msg'] = "";
	$element['err_msg'] = "";
	if (isset($_POST['register'])) { // form submitted
		// get the values of form fields
		// validate each field
		$this->form_validation->set_rules('name', 'Name', 'trim|required',
		    	'required' => 'Name is required')
		$this->form_validation->set_rules('email', 'Email Id', 'trim|required|valid_email|is_unique[]',
		    	'required' => 'Email Id is required',
		    	'is_unique' => 'This Email id is already registered')
		if (empty($_FILES['photo']['name'])) { 
			$this->form_validation->set_rules('photo', 'Photo', 'trim|required|xss_clean',
			array('required' => 'Photo is required'));
		if ($this->form_validation->run() == FALSE) {
			// validation not passed, so load the form again
		else {
		// validation is success, so go for upload photo
		// get upload path from config file
			if (!empty($_FILES['photo']['name'])) {
				$config['upload_path'] = $this->config->item('upload_file_path');
				$config['allowed_types'] = 'gif|jpg|png|jpeg';
				$config['max_size'] = 4096;  // max image size 4M
				$config['overwrite'] = FALSE;
				$config['remove_spaces'] = TRUE;  // change space in file name to underscore
				$this->load->library('upload', $config);
				if($this->upload->do_upload('photo')){  // successful upload
					$upload_data = $this->upload->data();
					$file_name = $upload_data['file_name'];
					$data = array('name'=>$name, 'email'=>$email, 'image'=>$file_name);
					$result = $this->ModelUpload->register($data);
					if ($result) { 
						$user_data['succ_msg'] = 'Registration successful';
						$user_data['image_path'] = $this->config->item('upload_file_path');
						$user_data['user'] = $this->ModelUpload->get_user($email);
					else { 
						$element['err_msg'] = "Error in Registration";
				else { // error in upload
					$element['err_msg'] = $this->upload->display_errors();
	else // if form is not submitted

Validations are performed on the input data name, email and photo using form_validation->set_rules() method. You can see for the email validation, valid_email and is_unique rules are used. For detail how to do form validation, you can read the topic How to Validate Form Data in CodeIgniter 3.

'upload_file_path' is defined in config.php. It loads CodeIgniter upload library with these config parameters. Then do_upload() method uploads the photo. Once upload is successful, it calls model's register() method to insert the data into the database table.

Step 4 - Write Model code (ModelUpload.php)

The Model class will have two methods, one for registration and other for user details. For registration, model method name is register(). This method takes the input data in an array and uses $db->insert() method to insert row in user_profile table.

get_user() method needs $email_id as parameter and select details of the user from user_profile table. So now let's see the code for these methods in the model:

Model Method register()

function register($data) {
  if (!empty($data)) {
    $result = $this->db->insert('user_profile', $data);
    return $result;

Model Method get_user()

function get_user($email_id) {
  $query = $this->db->get();
  return $query->row();

You can see, it uses CodeIgniter query builder class to generate the query. It just selects the row from user_profile table where input email matches the database value.

Step 5 - Update Configuration files and Test the Application

We will update below files in config folder and also, we will have .htaccess file in the root directory.

  1. Update autoload.php (application/config/autoload.php)

    We need to add 'database' and 'form_validation' in autoload libraries.

    Also, 'url' and 'form' are added in helper array.

    $autoload['libraries'] = array('database','form_validation');
    $autoload['helper'] = array('url','form');
  2. Update config file (application/config/config.php)

    We added 'upload_file_path' for the image path. This is used in the controller. Using this path photo is displayed in the view. Set 'base_url' and 'index_page' as below in this file:

    $config['base_url'] = 'http://localhost/ci_upload/';
    $config['upload_file_path'] = 'uploads/';
    $config['index_page'] = '';
  3. Update database setup file (application/config/database.php)

    We are using a database named 'demo' in localhost with user as 'root', updated database.php:

    $active_group = 'default';
    $query_builder = TRUE;
    $db['default'] = array(
    	'dsn'	=> '',
    	'hostname' => 'localhost',
    	'username' => 'root',
    	'password' => '',
    	'database' => 'demo',
    	'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
  4. Routes (application/config/routes.php)
    $route['default_controller'] = 'UploadController';
    $route['register'] = 'UploadController/register';
    $route['404_override'] = '';
    $route['translate_uri_dashes'] = FALSE;
  5. Update .htaccess (hypertext access) file to remove index.php from the URL
    RewriteEngine On
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteRule ^(.*)$ index.php?/$1 [L]

Test The Application

In the browser run localhost/ci_upload. You will see the home page displayed as below:

upload image file in codeigniter 3

Register a user with photo. Verify that file is uploaded in 'uploads' folder and a row is inserted in the database table 'user_profile'.

Also test the validation for registration form and the photo.

upload multiple images in codeigniter 3Conclusion

Uploading photo is very important part of registration form as profile photo is used in almost all user registration. I have tried to explain each step in detail for your easy understanding. Hope it was useful for you.