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

user_profile.sql


CREATE TABLE `user_profile` (
  `id` int(11) NOT NULL,
  `name` varchar(255) NOT NULL,
  `email` varchar(255) NOT NULL,
  `image` varchar(500) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

ALTER TABLE `user_profile`
  ADD PRIMARY KEY (`id`);

ALTER TABLE `user_profile`
  MODIFY `id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=1;

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

application/views/register.php


<!DOCTYPE html>
<html lang="en">
<head>
  <title>User Registration</title>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css">
  <link rel="stylesheet" href="<?php echo base_url('assets/css/style.css') ?>">
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
</head>
<body>
  <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> -->
    </div>
    <form id ="frm" action = "<?= base_url()?>register" method = "post" enctype="multipart/form-data">
      <div class="form-group col-md-12">
        <label>Name</label>
        <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>
      <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>
      <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>
               </p>
               <small color="blue">(Max size: 4MB, File type: jpg, jpeg, png, gif</small>
               <div class="error"><?php echo form_error('photo'); ?></div>
             </div>
             <div class="form-group col-md-5">
              <img id="prvwPhoto">
            </div>
          </div>
        </div>
        <div class="col-md-12 text-center">
        <input type ="submit" name="register" class="btn btn-primary" value="Submit">
      </div>
    </form>
  </div>
  </body>
  </html>

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:


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

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

application/views/view_profile.php


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

Stylesheet is given below for all these views.

assets/css/style.css


h4{
  margin-top: 20px;
  text-align: center;
}

#frm{
  width:40%;
  margin:auto;
}
label{
    font-weight: bold;
  }

.success{
  color:green;
  height: 10px;
}
.error{
  color:red;
  height: 10px;
}
.msg{
  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;
}
.profile{
  width: 50%;
  margin: auto;
}
.img-class{
  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(){
	$this->load->view('register');
}

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
		$name=$this->input->post('name');
		$email=$this->input->post('email');
		// validate each field
		$this->form_validation->set_rules('name', 'Name', 'trim|required',
		array(
		    	'required' => 'Name is required')
		);
		$this->form_validation->set_rules('email', 'Email Id', 'trim|required|valid_email|is_unique[user_profile.email]',
		    array(
		    	'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
			$this->load->view('register',$element);
			} 
		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);
						$this->load->view('view_profile',$user_data);
					}
					else { 
						$element['err_msg'] = "Error in Registration";
						$this->load->view('register',$element);	
					}
				}	
				else { // error in upload
					$element['err_msg'] = $this->upload->display_errors();
					$this->load->view('register',$element);	
				}
			}
		}
	}  
	else // if form is not submitted
	$this->load->view('register',$element);
}

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) {
  $this->db->select('*');
  $this->db->from('user_profile');
  $this->db->where('email',$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.