// Step 1: Load the form validation library in your controller
$this->load->library('form_validation');
// Step 2: Set rules for file upload in the validation configuration
$config['upload_path'] = './uploads/';
$config['allowed_types'] = 'gif|jpg|png'; // Define the allowed file types
$config['max_size'] = 100; // Maximum file size in kilobytes
$this->load->library('upload', $config);
// Step 3: Define the validation rules for the file upload field in your controller
$this->form_validation->set_rules('userfile', 'File', 'callback_file_check');
// Step 4: Create a callback function to check the file type
public function file_check($str) {
$allowed_mime_types = array('image/gif', 'image/jpeg', 'image/png');
$mime = get_mime_by_extension($_FILES['userfile']['name']);
if (in_array($mime, $allowed_mime_types)) {
return true;
} else {
$this->form_validation->set_message('file_check', 'Invalid file type. Please upload only GIF, JPG, or PNG images.');
return false;
}
}
// Step 5: Check if the form is submitted and validate it
if ($this->form_validation->run() == FALSE) {
// Form validation failed, display errors or redirect as needed
} else {
// Form validation passed, process the uploaded file
if (!$this->upload->do_upload('userfile')) {
// File upload failed, display errors
} else {
// File uploaded successfully, continue with further processing
$data = $this->upload->data();
// Additional processing logic here
}
}