Codeigniter 4 – Upload image with Example

Configuring the Upload Library

- Open the app/Config/Upload.php file.
- Set the allowedTypes to the types of files you want to allow.
- Set the maxSize to the maximum file size.

Example:

public $allowedTypes = ['jpg', 'png', 'gif'];
public $maxSize = 1024; // 1MB

Creating the Upload Form

- Create a new file in the app/Views directory.
- Use HTML to create the form.

Example:

<form action="<?= site_url('upload/image') ?>" method="post" enctype="multipart/form-data">
    <input type="file" name="image">
    <input type="submit" value="Upload">
</form>

Using the Upload Library

- Use the upload() method to upload the image.

Example:

public function image()
{
    $image = $this->request->getFile('image');
    $upload = $this->upload->upload($image);
    if (!$upload) {
        // Upload failed
    } else {
        // Upload successful
    }
}

Saving the Uploaded Image

- Use the move() method to save the uploaded image.

Example:

if ($upload) {
    $image->move('uploads');
}

Retrieving the Uploaded Image

- Use the getName() method to get the name of the uploaded image.

Example:

$imageName = $image->getName();

I hope this helps! Let me know if you have any further questions or need more information.

Note: Uploading images with the Upload Library in CodeIgniter 4 provides a simple and intuitive way to handle file uploads. It helps to improve the security and reliability of your application.

Leave a Reply

Shopping cart0
There are no products in the cart!
Continue shopping
0