CodeIgniter Basic Tutorial
Performance & Utilities
CodeIgniter Advanced
File uploading is a very common feature in web applications. CodeIgniter makes file upload handling easy and secure using its File Uploading Class.
With just a few lines of configuration, you can upload images, documents, and other file types.
First, create a simple HTML form in application/views/upload_form.php
:
<!DOCTYPE html> <html> <head> <title>File Upload in CodeIgniter</title> </head> <body> <h2>Upload a File</h2> <!-- Show error message if any --> <?php if(isset($error)) { echo $error; } ?> <!-- Show success message --> <?php if(isset($success)) { echo $success; } ?> <!-- Upload form --> <?php echo form_open_multipart('upload/do_upload'); ?> <input type="file" name="userfile" size="20" /> <br><br> <input type="submit" value="Upload" /> </form> </body> </html>
Create application/controllers/Upload.php
:
<?php defined('BASEPATH') OR exit('No direct script access allowed'); class Upload extends CI_Controller { public function __construct() { parent::__construct(); $this->load->helper(array('form', 'url')); } public function index() { $this->load->view('upload_form', array('error' => ' ' )); } public function do_upload() { $config['upload_path'] = './uploads/'; // Folder where files will be uploaded $config['allowed_types'] = 'gif|jpg|png|pdf|docx'; $config['max_size'] = 2048; // 2MB $config['max_width'] = 2000; $config['max_height'] = 2000; $this->load->library('upload', $config); if (!$this->upload->do_upload('userfile')) { // Upload failed → show error $error = array('error' => $this->upload->display_errors()); $this->load->view('upload_form', $error); } else { // Upload success → show file data $data = array('success' => 'File uploaded successfully!', 'file_data' => $this->upload->data()); $this->load->view('upload_form', $data); } } }
Make sure you create an uploads
folder in your project’s root directory:
/application /system /uploads ← create this folder
⚠️ Give write permissions to the uploads
folder.
You can control how uploads work with these preferences:
jpg|png|gif
).Example (renaming file):
$config['file_name'] = 'my_custom_name';
After successful upload, you can access details:
$fileData = $this->upload->data(); echo "File Name: " . $fileData['file_name']; echo "File Size: " . $fileData['file_size']; echo "File Path: " . $fileData['full_path'];
You can also upload multiple files by looping through $_FILES
:
foreach ($_FILES['userfiles']['name'] as $key => $name) { $_FILES['file']['name'] = $_FILES['userfiles']['name'][$key]; $_FILES['file']['type'] = $_FILES['userfiles']['type'][$key]; $_FILES['file']['tmp_name'] = $_FILES['userfiles']['tmp_name'][$key]; $_FILES['file']['error'] = $_FILES['userfiles']['error'][$key]; $_FILES['file']['size'] = $_FILES['userfiles']['size'][$key]; if ($this->upload->do_upload('file')) { $data = $this->upload->data(); echo "Uploaded: " . $data['file_name'] . "<br>"; } }