How To File Upload In CodeIgniter 4 Example

How To File Upload In CodeIgniter 4 Example

Hello friends, Today we will show How To File Upload In CodeIgniter 4 Example. We will show example of CodeIgniter 4 if file upload. we will explain how to use file upload in CodeIgniter 4. You will learn how to file upload using CodeIgniter 4.

CodeIgniter comes with default File Uploading class. Which makes your image and other documents easily upload on the server. So let’s following CodeIgniter 4 Image upload example.

File Upload In CodeIgniter 4 Example

Step 1 : Set Up CodeIgniter Application

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

composer create-project codeigniter4/appstarter

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

Go inside the project folder.

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 . 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 bellow 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

$routes->get('/', 'FileUpload::index');

Step 7 : Create View

Now, we need to create a file uploading HTML component using Bootstrap. So, create app/Views/home.php file and place the given following 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 - web-tuts.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 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 4:

http://localhost:8080

I hope you understand of How To File Upload In Example using CodeIgniter 4 Tutorial and it can help you…

Read Also :  Codeigniter Paypal Integration Example Tutorial