File uploading in CodeIgniter has two primary parts—the frontend and the backend. The frontend is taken care of by the HTML form that uses the form input type file. On the backend, the file upload library forms the submitted input from the form and writes it to the transfer registry.
This tutorial discusses the process of creating a CodeIgniter based file upload component that could be easily used to upload images and other files with ease. You could validate and even restrict file size and type during the upload process.
Folder Creation
The first step is the creation of two folders that form the basis of the upload process. The first folder is the destination folder that would receive the uploaded files.
Next, go to the root of the CI installation and create a folder named “uploads”.
Go to the view folder (located at the root of the CI installation) and create two new “view” files. Name these files file_view.php (displays the form containing file upload fields) and upload_success.php (displays the upload successful message).
Nothing as Easy as Deploying CodeIgniter Apps on Cloud
With Cloudways, you can have your CodeIgniter apps up and running on managed cloud servers in just a few minutes.
Create the Controller
The next step is the creation of a file in the controller folder. Name the file upload_controller.php. In this file, I will load a library for initializing the Upload class through the following code:
$this->load->library('upload');
Set File Upload Preferences
I will also set the preferences for the file upload process through the controller function do_upload(). this function will contain the following code:
$config['upload_path'] = './uploads/'; $config['allowed_types'] = 'gif|jpg|png'; $config['max_size'] = '100'; $config['max_width'] = '1024'; $config['max_height'] = '768';
As you could see, through this function, you could easily restrict the upload path, allowed file types, maximum size and dimensions of the image.
you could see this function in action when you call the file_view.php file. if you are at a staging domain, use the URL: your-domain/ci_demo/index.php/upload_controller/file_view OR in the case of loclhost: localhost/ci_demo/index.php/upload_controller/file_view
Related: How To Host CodeIgniter PHP On Cloud
The Form Helper
Note that file upload requires a multipart form. For this, I have included a form helper in the controller with the following syntax:
$this->load->helper(array('form', 'url'));
You Might Also Like: Simple Guide to CodeIgniter Form Validation
Structural View
For the structure of the image upload, I will start by creating a file in the views folder with the name custom_view.php. Open this file and add the following code to it:
<html> <head> <title>File Upload In Codeigniter</title> </head> <body> <?php echo $error;?> <?php echo form_open_multipart('upload_controller/do_upload');?> <?php echo "<input type='file' name='userfile' size='20' />"; ?> <?php echo "<input type='submit' name='submit' value='upload' /> ";?> <?php echo "</form>"?> </body> </html>
Next, go to the controller folder and create a new file with the name upload_controller.php
You might also like: How To Pass Data From Controller To View In CodeIgniter
Add the following code to this file:
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed'); class Upload_Controller extends CI_Controller { public function __construct() { parent::__construct(); } public function custom_view(){ $this->load->view('custom_view', array('error' => ' ' )); } public function do_upload(){ $config = array( 'upload_path' => "./uploads/", 'allowed_types' => "gif|jpg|png|jpeg|pdf", 'overwrite' => TRUE, 'max_size' => "2048000", // Can be set to particular file size , here it is 2 MB(2048 Kb) 'max_height' => "768", 'max_width' => "1024" ); $this->load->library('upload', $config); if($this->upload->do_upload()) { $data = array('upload_data' => $this->upload->data()); $this->load->view('upload_success',$data); } else { $error = array('error' => $this->upload->display_errors()); $this->load->view('custom_view', $error); } } } ?>
Notice that the array $config of the do_upload() has an element named allowed_types. You could use the parameters of this element to change the allowed file types. For example, to allow a range of files, use the following structure of this element:
'allowed_types' => "gif|jpg|jpeg|png|iso|dmg|zip|rar|doc|docx|xls|xlsx|ppt|pptx|csv|ods|odt|odp|pdf|rtf|sxc|sxi|txt|exe|avi|mpeg|mp3|mp4|3gp",
The Success Message
To display the upload successful message, I will use the upload_success.php file (located in the view folder). Add the following code to it:
<html> <head> <title>Success Message</title> </head> <body> <h3>Congragulation You Have Successfuly Uploaded</h3> <!-- Uploaded file specification will show up here --> <ul> <?php foreach ($upload_data as $item => $value):?> <li><?php echo $item;?>: <?php echo $value;?></li> <?php endforeach; ?> </ul> <p><?php echo anchor('upload_controller/file_view', 'Upload Another File!'); ?></p> </body> </html>
Note: Make sure that you are calling the correct path for the controller class
Related: How To Create A REST API In CodeIgniter
Conclusion
This was a short tutorial on creating an image and file upload process in a CodeIgniter powered application. Remember that you could easily modify the allowed file types and image parameters through the code. Additionally, for those deploying their CodeIgniter applications, consider exploring CodeIgniter Hosting solutions. These specialized hosting providers often have pre-configured environments that streamline the deployment process and might offer additional features optimized for CodeIgniter’s performance.
If you need help in understanding the code or integrating the code into your CI application, do leave a comment below.
Frequently Asked Questions
Are there any specific CodeIgniter libraries or helpers available for handling file uploads?
Yes, CodeIgniter includes a built-in “Upload” library for efficient handling of file uploads, managing tasks such as validation, and relocating the file to a permanent location.
Are there any considerations for optimizing performance and handling large file uploads in CodeIgniter?
To manage large file uploads in CodeIgniter, consider factors like PHP settings, CodeIgniter configurations, server configuration, chunked file uploads, validation, error handling, post-upload cleanup, and file storage.
How can I display uploaded images or files on the frontend using CodeIgniter?
You can display uploaded images or files in CodeIgniter by providing a link or path to the file’s server location. For instance, using an HTML tag with the src attribute set to the file’s location.
Are there any security considerations when handling file uploads in CodeIgniter?
Take the following security considerations for file uploads in CodeIgniter:
- Implement thorough file validation.
- Restrict permitted file types based on your needs.
- Set an upload size limit.
- Rename uploaded files to mitigate the risk of script execution or file overwrites.
- Store files outside the web root or apply access controls to prevent unauthorized access.
- Perform virus scans on uploaded files.
- Ensure correct file permissions are set.
What are some common troubleshooting tips for resolving issues with file and image uploads in CodeIgniter?
Here are some common troubleshooting tips for resolving issues with file and image uploads in CodeIgniter:
- Confirm correct file and folder permissions.
- Review PHP configuration settings.
- Scrutinize CodeIgniter configurations.
- Validate form rules.
- Analyze error messages.
- Enable debugging and logging.
- Conduct tests in various environments.
Owais Alam
is the WordPress Community Manager at Cloudways - A Managed WooCommerce Hosting Platform and a seasoned PHP developer. He loves to develop all sorts of websites on WordPress and is in love with WooCommerce in particular. You can email him at [email protected]