How To File Upload In Example using Codeigniter 4 Tutorial

Sep 21, 2021 . Admin



Hello Friends,

Now let's see example of how to use file upload in codeigniter 4. This is a short guide on codeigniter 4 if file upload. Here you will learn how to use file upload in codeigniter 4. We will use how to use if file upload using codeigniter 4. Let's get started with how to file upload use in codeigniter 4.

Here i will give you many example how you can use file upload in codeigniter 4.

Step 1 : Set Up Codeigniter Application

Hit the below command to install the CodeIgniter 4 application, but you must have a composer package installed on your device.

<?php
composer create-project codeigniter4/appstarter
?>

Rename the Codeigniter app name, such as codeigniter-file-upload.

Go inside the project folder.

<?php cd codeigniter-file-upload ?> Step 2 : Enable Errors in CI

Enable error reporting to debug the error with gravitas in the Codeigniter application.

Open app/Config/Boot/development.php file and set the display_errors to 1 instead of 0. Do the same thing in app/Config/Boot/production.php file.

ini_set('display_errors', '1');
Step 3 : Formulate Database with Table

Go to PHPMyAdmin, execute the following SQL query to manifest a database with demo name, also create a users table within. Here we store the uploaded files or images.

CREATE TABLE users (
    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',
    PRIMARY KEY (id)
) ENGINE=InnoDB DEFAULT CHARSET=latin1 COMMENT='users table' AUTO_INCREMENT=1;
Step 4 : Database Connection

To establish the coherence between database and codeigniter you must define database name, username and password in application/config/database.php.

public $default = [
    'DSN'      => '',
    'hostname' => 'localhost',
    'username' => 'test',
    'password' => '4Mu99BhzK8dr4vF1',
    'database' => 'demo',
    'DBDriver' => 'MySQLi',
    'DBPrefix' => '',
    'pConnect' => false,
    'DBDebug'  => (ENVIRONMENT !== 'development'),
    'cacheOn'  => false,
    'cacheDir' => '',
    'charset'  => 'utf8',
    'DBCollat' => 'utf8_general_ci',
    'swapPre'  => '',
    'encrypt'  => false,
    'compress' => false,
    'strictOn' => false,
    'failover' => [],
    'port'     => 3306,
];
CodeIgniter\Database\Exceptions\DatabaseException

There are a high chance that you might get Unable to connect database : Codeigniter the error, especially if you are working with MAMP or XAMP servers. You can define either of the hostname for MAMP or XAMP.

# XAMP
public $default = [
    'hostname' => '/Applications/XAMPP/xamppfiles/var/mysql/mysql.sock',
]

# MAMP
public $default = [
    'hostname' => '/Applications/MAMP/tmp/mysql/mysql.sock',
]
Step 5 : Create Image Upload Controller

Create a FileUpload.php controller in app/Controllers directory. Then, place the below-mentioned code in it.

<?php 
namespace App\Controllers;
use CodeIgniter\Controller;

class FileUpload extends Controller
{
    public function index() 
    {
        return view('home');
    }

    function upload() 
    { 
        helper(['form', 'url']);
        $database = \Config\Database::connect();
        $db = $database->table('users');
        $input = $this->validate([
            'file' => [
                'uploaded[file]',
                'mime_in[file,image/jpg,image/jpeg,image/png]',
                'max_size[file,1024]',
            ]
        ]);
    
        if (!$input) {
            print_r('Choose a valid file');
        } else {
            $img = $this->request->getFile('file');
            $img->move(WRITEPATH . 'uploads');
            $data = [
               'name' =>  $img->getName(),
               'type'  => $img->getClientMimeType()
            ];
            $save = $db->insert($data);
            print_r('File has successfully uploaded');        
        }
    }
}
Step 6 : Create Routes

We have to create a route that loads the file uploading controller when the application starts. Open app/Config/Routes.php file and add the following code.

$routes->get('/', 'FileUpload::index');
Step 7 : Create View

Eventually, we require to create a file uploading HTML component using Bootstrap. So, create app/Views/home.php file and place the given below code in it.

<!doctype html>
<html lang="en">
<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
    <title>How To File Upload in Codeigniter 4 Example Tutorial - MyWebtuts.com</title>
    <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/css/bootstrap.min.css">
    <style>
        .container {
          max-width: 500px;
        }
    </style>
</head>

<body>
    <div class="container mt-5">
        <form method="post" action="<?php echo base_url('FileUpload/upload');?>" enctype="multipart/form-data">
            <div class="form-group">
                <label>Avatar</label>
                <input type="file" name="file" class="form-control">
            </div>

            <div class="form-group">
                <button type="submit" class="btn btn-danger">Upload</button>
            </div>
        </form>
    </div>
</body>
</html>
Step 8 : Start Application

Let us start the app, run the following command to start the application:

php spark serve

Enter the following URL in the browser to upload the image into the database in Codeigniter:

http://localhost:8080

It will help you....

#Codeigniter 4 #Codeigniter