CodeIgniter has a file upload library that can be used to upload an image or a file to the server. If you load the upload library with some config parameters, you can use the 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. We will see CodeIgniter 3 form validation and image validation. We will display the photo after successful registration.
Create a table for user profiles
We will create a table named 'user_profile' in a MySQL database. This table will store user details - name, email and photo. The table structure is given below:
Table: user_profile
Below are the columns in this table.
- id - User id, primary key and auto incremented
- name - Name of the user
- email - Email of the user
- 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
) 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 create a folder named 'ci_upload' under xampp/htdocs and keep all CodeIgniter folder/files in this folder along with our custom files.
We will have the Controller - UploadController.php
, Model - ModelUpload.php
and two views (register.php
and view_profile.php
).
Also, we will use a folder named 'uploads' under the root directory to store the uploaded images.
Create the views for user registration and view profile
The view for registration with a photo is a simple form with the user's name, email id and photo. Users can fill in their name and email id and then select a photo as a 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 the user selects a photo, a JavaScript function previewPhoto()
is called on the onChange
event of the input photo. After submitting the form, all 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, the 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>
The View to display user profile
After the form is submitted and processed successfully, it displays the data using another view called view_profile.php
.
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.
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%;
}
}
Write Controller code (UploadController.php) to complete upload and registration
Our controller will have an index()
method to display the registration page and a register()
method to process submitted data and upload the photo.
Controller method index()
The index() method loads the view that displays the 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 is executed when the user submits the form. It does the form validation and calls a model method to insert the data into the "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. For the email validation, two rules are used - valid_email
and is_unique
. For detailed form validation, you can read the topic How to do Form Validation in CodeIgniter 3.
'upload_file_path' is defined in config.php
. It loads the CodeIgniter upload library with these config parameters. Then do_upload()
method uploads the photo. Once the upload is successful, it calls the model's register()
method to insert the data into the database table.
Write Model code (ModelUpload.php)
The Model class will have two methods, one for registration and the other for user details. register() method takes the input data in an array and uses $db->insert()
method to insert a row into the 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 that it uses the CodeIgniter query builder class to generate the query. It selects the row from the user_profile table where the input email matches the database value.
Update Configuration files and Test the Application
We will update the below files in the config folder and create .htaccess file in the root directory.
- Update autoload.php (application/config/autoload.php)
Add 'database' and 'form_validation' in autoload libraries. Add 'url' and 'form' in the helper array.
$autoload['libraries'] = array('database','form_validation');
$autoload['helper'] = array('url','form');
- 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'] = '';
- Update database setup file (application/config/database.php)
Update the database name and userid/password in 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
);
- Routes (application/config/routes.php)
$route['default_controller'] = 'UploadController';
$route['register'] = 'UploadController/register';
$route['404_override'] = '';
$route['translate_uri_dashes'] = FALSE;
- 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 as displayed below:
Register a user with a photo. Verify that the file is uploaded in the 'uploads' folder and a row is inserted in the database table 'user_profile'.
Also, test the validation for the registration form and the photo.
Conclusion
Uploading a photo is an important part of the registration form as a profile photo is used in almost all user registration. I have tried to explain each step in detail for your easy understanding. I hope it will be useful to you.
Post a Comment