• Mail Us:

Upload files and images in Codeigniter 4

Please Login and enroll in this course to view the lesson.

Uploading the image/images/files in Codeigniter 4 is very easy; you need to use a few methods, that's it.

Codeigniter 4 provides the upload library/class to upload the images/files out of the box.

Here is the HTML

<!doctype html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport"
          content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Welcome in Register</title>
</head>
<body>
    <div>
        <?php
        $myvalidation  = ConfigServices::validation();
        echo $myvalidation->listErrors();
        ?>
    </div>
    <?php echo form_open_multipart('libraries/newuser',['class'=>'muclass','id'=>'myId'])?>
    <p>
        <?php echo form_upload('image1','','')?>
    </p>
    <?php echo form_submit('submit','Register Now'); ?>
    <?php echo form_close(); ?>
</body>
</html>

And this is the controller to receive the images/file.

<?php
namespace AppControllers;


use AppModelsModUser;

class Libraries extends BaseController
{
  
    public function register()
    {
        helper('form');
        echo view('user/register');
    }

    public function newuser()
    {
       
        $request  = ConfigServices::request();
        
        $randomName = '';
        
            $fileName = $request->getFile('image1');
            if (!empty($fileName) && $fileName->getSize() > 0) {
                $randomName = $fileName->getRandomName();
                $fileName->move('./public/assets/images/',$randomName);
            }
            else{
                $imgName = $fileName->getError();
            }
            $userData = [
             
                'u_dp'=>$randomName,

            ];
           

    }

   
}//class here

Make sure you have to create the two folders in the public directory assets and images.