File Upload Validation in CodeIgniter

199

CodeIgniter provides a form validation class that helps to validate form fields by writing the minimal code. Generally, we are used required rule in CodeIgniter to validate a required form field. But required rule does not work when you tried to validate a file upload field in CodeIgniter. In this CodeIgniter tutorial, we will show you how to add validation to file upload in CodeIgniter.

For better understanding, we’ll demonstrate the complete file upload process with file upload validation. Using our example code you can implement file or image upload functionality with file input field validation in CodeIgniter.

Upload Directory

You need to create a directory to store the uploaded files. For example, this script uploads files to the uploads/files/directory.

Controller (Files.php)

The Files controller contains 2 functions, upload() and file_check().

The upload() function handles the following functionality.

  • Loads the file upload form.
  • Validates file input field to check whether it is empty or the file type is not supported.
  • Uploads the submitted file to the server.

The following built-in CodeIgniter library and helper are used to upload files with validation in CodeIgniter.

  • form_validation – helps to validate form fields.
  • file – provides get_mime_by_extension() function to get the mime type of uploaded file.
  • upload – helps to upload the file to the server.

The file_check() is a validation callback function that checks whether the file input field is empty or selected file is not allowed.

View (files/upload.php)

This view file contains upload form HTML that allows user to select a file for upload. The form is submitted to the upload() method of Files controller for validation and upload.

 

Leave A Reply

Your email address will not be published.