In this tutorial you will learn about the codeigniter 4 image upload example tutorial and its application with practical example.
In this codeigniter 4 image upload example tutorial I will show you how to upload image fine in codeigniter 4. In this tutorial you will learn to upload image file in codeigniter 4. I will also show you how to validate upload image into folder and then save it into database. In this tutorial before saving image into database we will validate image and then save it into directory using. Before uploading the image we will perform server side validation. In this article we will create a simple example to upload image in codeigniter 4.
codeigniter 4 image upload example tutorial
In this step by step tutorial I will demonstrate you with example how to upload image file in codeigniter 4. Please follow the instruction given below:
- Install Codeigniter
- Basic Configurations
- Create a Database in table
- Connect to Database
- Create Controller and Model
- Create Views Files
- Run The Application
Install Codeigniter 4
Download or install the latest version of CodeIgniter 4
Basic Configurations
Now, we need to setup some codeigniter basic configurations in your project as following.
1 2 3 4 5 6 7 8 9 10 |
//change the baseUrl public $baseURL = 'http://localhost:8080'; To public $baseURL = 'http://localhost/your_project_name/'; //remove the index.php from indexPage public $indexPage = ''; //change the uriProtocol public $uriProtocol = 'REQUEST_URI'; To public $uriProtocol = 'PATH_INFO'; |
Create a Database in table
Now you need to create some database tables in your codeigniter application database. Please use the following sql query to create database tables.
1 2 3 4 5 6 7 8 9 10 |
CREATE TABLE IF NOT EXISTS `students` ( `id` int(11) NOT NULL AUTO_INCREMENT, `first_name` varchar(64) NOT NULL, `last_name` varchar(64) NOT NULL, `address` text NOT NULL, `email` varchar(64) NOT NULL, `mobile` varchar(12) NOT NULL, `image` varchar(164) NOT NULL, PRIMARY KEY (`id`) ) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=15 ; |
Connect to Database
Now, lets create a MySQL database and connect it with codeigniter application. After creating database we need to set database credential in application’s app/Config/Database.php file.
app/Config/Database.php
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 |
public $default = [ 'DSN' => '', 'hostname' => 'localhost', 'username' => 'root', 'password' => '', 'database' => 'codeigniter4_jqurey_validation', 'DBDriver' => 'MySQLi', 'DBPrefix' => '', 'pConnect' => false, 'DBDebug' => (ENVIRONMENT !== 'production'), 'cacheOn' => false, 'cacheDir' => '', 'charset' => 'utf8', 'DBCollat' => 'utf8_general_ci', 'swapPre' => '', 'encrypt' => false, 'compress' => false, 'strictOn' => false, 'failover' => [], 'port' => 3306, ]; |
Create Controller and Model
In this step we will create a “Student.php” controller file and the “StudentModel.php” model file. Please paste the below code in corresponding file.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 |
<?php namespace App\Controllers; use CodeIgniter\Controller; use App\Models\StudentModel; class Student extends Controller { public function __construct() { helper(['form', 'url']); } public function index() { return view('add'); } public function store() { $rules = [ 'txtFname' => 'required', 'txtLname' => 'required', 'txtEmail' => 'required|valid_email', 'txtMobile' => 'required|min_length[10]|numeric', 'txtAddress' => 'required', 'image' => [ 'uploaded[image]', 'mime_in[image,image/jpg,image/jpeg,image/gif,image/png]', 'max_size[image,4096]', ], ]; if (!$this->validate($rules)) { return view('add', ['validation' => $this->validator]); } else { $image = $this->request->getFile('image'); $image->move(WRITEPATH . 'uploads'); $data = [ 'first_name' => $this->request->getVar('txtFname'), 'last_name' => $this->request->getVar('txtLname'), 'email' => $this->request->getVar('txtEmail'), 'mobile' => $this->request->getVar('txtMobile'), 'address' => $this->request->getVar('txtAddress'), 'image' => $image->getClientName(), ]; $model = new StudentModel(); $save = $model->insert($data); return redirect()->to( base_url('student') ); } } } ?> |
app/Models/StudentModel.php
1 2 3 4 5 6 7 8 9 10 11 12 |
<?php namespace App\Models; use CodeIgniter\Database\ConnectionInterface; use CodeIgniter\Model; class StudentModel extends Model { protected $table = 'Students'; protected $allowedFields = ['first_name','last_name','address','email', 'mobile','image']; } ?> |
Create Views Files
Now, in this step we will create a view file and put following code in it.
app/views/add.php
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 |
<!DOCTYPE html> <html> <head> <title>CodeIgniter 4 Image Upload With Preview Example </title> <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css"> <script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.js"></script> <style> .hideImage{ display:none; } #preview-image{ margin-top:10px; width:200px; height:200px; } </style> </head> <body> <div class="container"> <div class="row"> <div class="col-md-9"> <h2>Add Student</h2> </div> </div> <div class="row"> <div class="col-md-9"> <?= \Config\Services::validation()->listErrors(); ?> <form method="post" name="frmAddStudent" id="frmAddStudent" action="<?php echo site_url('student/store');?>" enctype="multipart/form-data"> <div class="form-group"> <label for="txtFname">First Name</label> <input type="text" name="txtFname" class="form-control" id="txtFname" placeholder="Please enter first name" /> </div> <div class="form-group"> <label for="txtLname">Last Name</label> <input type="text" name="txtLname" class="form-control" id="txtLname" placeholder="Please enter last name" /> </div> <div class="form-group"> <label for="txtEmail">Email</label> <input type="text" name="txtEmail" class="form-control" id="txtEmail" placeholder="Please enter email" /> </div> <div class="form-group"> <label for="txtMobile">Mobile</label> <input type="text" name="txtMobile" class="form-control" id="txtMobile" placeholder="Please enter mobile number." /> </div> <div class="form-group"> <label for="txtAddress">Address</label> <textarea name="txtAddress" class="form-control"></textarea> </div> <div class="form-group"> <label for="image">Image</label> <input type="file" name="image" class="form-control" id="image" onchange="previewImageFile(this);" accept=".png, .jpg, .jpeg" /> <img src="" alt="Image preview" id="preview-image" class="hideImage"> </div> <div class="form-group"> <input type="submit" value="Add" name="btnadd" id="btnadd" class="btn btn-success" /> </div> </form> </div> </div> <span class="d-none alert alert-success mb-3" id="res_message"></span> </div> <script> function previewImageFile(input, id) { var output = document.getElementById('preview-image'); output.removeAttribute("class"); output.src = URL.createObjectURL(event.target.files[0]); output.onload = function() { URL.revokeObjectURL(output.src) } } </script> </body> </html> |
Run The Application
Now we are ready to run our example so lets start the development server using following artisan command –
1 |
php spark serve |
Now, open the following URL in browser to see the output –
1 |
http://localhost:8080/student |