CodeIgniter 4 Image File Upload Example

In this codeigniter tutorial, we will show you how to upload an image file in CodeIgniter 4 projects with server-side validation. You can use this tutorial as a guide to learn how to upload other types of files like PDFs and save them in the database.

To start, we will create a form that includes a file input field for selecting the file to upload. We will also define validation rules for the file to ensure that it meets the required criteria. Once the file is validated, we will insert it into the database and upload it to a specified folder.

By following this tutorial, you will be able to upload image files in CodeIgniter 4 with server-side validation and store them in the database or a designated folder.

Image File Upload in Codeigniter 4 Apps

Follow the below steps and easily upload files in a folder and store in the database in CodeIgniter 4 projects with validation:

  • Download Codeigniter Latest
  • Basic Configurations
  • Create Database With Table
  • Setup Database Credentials
  • Create Controller
  • Create Views
  • Start Development server

Step 1: Download Codeigniter Project

Let’s begin by downloading the latest version of CodeIgniter 4 from the official website. You can download it from this link: https://codeigniter.com/download. Once downloaded, extract the files and save them in your local system’s xampp/htdocs/ directory.

Now, change the folder name to “demo” to make it easy to remember and work with. This step is important as we will be using the CodeIgniter 4 framework for our image file upload example.

Step 2: Basic Configurations

In the next step, we need to make some basic configurations to the app/config/app.php file. To do this, we will go to the application/config/ directory and open the config.php file in a text editor.

Set Base URL Like This

public $baseURL = 'http://localhost:8080';
To
public $baseURL = 'http://localhost/demo/';

Step 3: Create Database With Table

In this step, we will create a database named “demo”. To do this, we will open our PHPMyAdmin and create a new database with the name “demo”.

Once the database is successfully created, we will need to use an SQL query to create a table in the database. This table will be used to store our image file data.

It is important to note that the table structure should match the requirements of our image file upload example. So, make sure to use the correct SQL query while creating the table.

CREATE TABLE files (
    id int(11) NOT NULL AUTO_INCREMENT COMMENT 'Primary Key',
    name varchar(100) NOT NULL COMMENT 'Name',
    type varchar(255) NOT NULL COMMENT 'file type',
    created_at varchar(20) NOT NULL COMMENT 'Created date',
    PRIMARY KEY (id)
  ) ENGINE=InnoDB DEFAULT CHARSET=latin1 COMMENT='demo table' AUTO_INCREMENT=1;

Step 4: Setup Database Credentials

In this step, we will connect our CodeIgniter 4 project to the database. To do this, we need to go to the app/Config/Database.php file and open it in a text editor.

Once we have opened the file, we will need to set up the database credentials. This means we need to provide the database name, username, and password.

It is important to note that the database credentials should match the database that we created in the previous step. Once we have added the credentials, we can save the file. This will allow our CodeIgniter 4 project to connect to the database.

public $default = [
    'DSN'      => '',
    'hostname' => 'localhost',
    'username' => 'root',
    'password' => '',
    'database' => 'demo',
    '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,
];

Step 5: Create Controller

Now Go to app/Controllers and create a controller name Form.php. In this controller, we will create some method/function. We will build some of the methods like :

  • Index() – This is used to display file/image upload form.
  • Store() – This is used to validate form file/image on server-side and store into MySQL database and folder.
<?php namespace App\Controllers;
 
use CodeIgniter\Controller;
 
class Form extends Controller
{
    public function index()
    {    
         return view('form');
    }
 
   public function store()
   {  
 
     helper(['form', 'url']);
         
     $db      = \Config\Database::connect();
         $builder = $db->table('file');
 
        $validated = $this->validate([
            'file' => [
                'uploaded[file]',
                'mime_in[file,image/jpg,image/jpeg,image/gif,image/png]',
                'max_size[file,4096]',
            ],
        ]);
 
        $msg = 'Please select a valid file';
  
        if ($validated) {
            $avatar = $this->request->getFile('file');
            $avatar->move(WRITEPATH . 'uploads');
 
          $data = [
 
            'name' =>  $avatar->getClientName(),
            'type'  => $avatar->getClientMimeType()
          ];
 
          $save = $builder->insert($data);
          $msg = 'File has been uploaded';
        }
 
       return redirect()->to( base_url('public/index.php/form') )->with('msg', $msg);
 
    }
}

Step 6: Create Views

Now we need to create form.php, go to application/views/ folder and create form.php file. and update the following HTML into your files:

<!DOCTYPE html>
<html>
<head>
  <title>Codeigniter 4 Image upload example - Torque Programming</title>
 <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css">
 
</head>
<body>
 <div class="container">
    <br>
     
    <?php if (session('msg')) : ?>
        <div class="alert alert-info alert-dismissible">
            <?= session('msg') ?>
            <button type="button" class="close" data-dismiss="alert"><span>×</span></button>
        </div>
    <?php endif ?>
 
    <div class="row">
      <div class="col-md-9">
        <form action="<?php echo base_url('public/index.php/form/store');?>" name="ajax_form" id="ajax_form" method="post" accept-charset="utf-8" enctype="multipart/form-data">
 
          <div class="form-group">
            <label for="formGroupExampleInput">Name</label>
            <input type="file" name="file" class="form-control" id="file">
          </div> 
 
          <div class="form-group">
           <button type="submit" id="send_form" class="btn btn-success">Submit</button>
          </div>
          
        </form>
      </div>
 
    </div>
  
</div>
</body>
</html>

This below line display error messages on your web page:

<?php if (session('msg')) : ?>
     <div class="alert alert-info alert-dismissible">
         <?= session('msg') ?>
         <button type="button" class="close" data-dismiss="alert"><span>×</span></button>
     </div>
 <?php endif ?>

Step 7: Start Development server

For start development server, Go to the browser and hit below the URL.

http://localhost/demo/public/index.php/form

Conclusion

In this Codeigniter 4 file upload example tutorial. You have learned how to upload files/images in CodeIgniter 4 projects with server-side validation.

You May Also Like

  1. React JS CRUD with CodeIgniter 4 and MySQL 8
  2. Send Email in CodeIgniter 4 With SMTP
  3. Codeigniter 4 Application Folder / Directory Structure
  4. Install / Download Codeigniter 4 By Manual, Composer, Git
  5. How to Install CodeIgniter 4 in Xampp
  6. Codeigniter 4 Create Controller, Model, View Example
  7. Codeigniter 4 Form Validation Tutorial with Example

Leave a Reply

Your email address will not be published. Required fields are marked *