In CodeIgniter, you can validate and process uploaded files using CodeIgniter's form validation library and file upload library.
1. Set Up File Upload Preferences:
Configure file upload preferences in application/config/config.php as mentioned in the previous response.
2. Create a Form:
Create a form in your view file (upload_form.php) to allow users to select and upload files:
<!-- upload_form.php -->
<?php echo form_open_multipart('upload/do_upload'); ?>
<input type="file" name="userfile" size="20" />
<br /><br />
<input type="submit" value="Upload" />
<?php echo form_close(); ?>
3. Create Controller Method to Handle Upload:
Create a controller (Upload.php) and define a method to handle file uploads. In this method, perform file validation using CodeIgniter's form validation library and process the uploaded file using CodeIgniter's file upload library:
// Upload.php controller
class Upload extends CI_Controller {
public function __construct() {
parent::__construct();
$this->load->helper(array('form', 'url'));
$this->load->library('form_validation');
}
public function index() {
$this->load->view('upload_form');
}
public function do_upload() {
$config['upload_path'] = './uploads/';
$config['allowed_types'] = 'gif|jpg|png';
$config['max_size'] = 100;
$config['max_width'] = 1024;
$config['max_height'] = 768;
$this->load->library('upload', $config);
if (!$this->upload->do_upload('userfile')) {
$error = array('error' => $this->upload->display_errors());
$this->load->view('upload_form', $error);
} else {
$data = array('upload_data' => $this->upload->data());
$this->load->view('upload_success', $data);
}
}
}
4. Add File Validation Rules:
Add file validation rules in the do_upload method using CodeIgniter's form validation library. You can add rules to check the file type, size, dimensions, etc.
$this->form_validation->set_rules('userfile', 'File', 'required');
if ($this->form_validation->run() == false) {
$this->load->view('upload_form');
} else {
// Process the uploaded file
}
5. Handle Upload Success:
Create a view (upload_success.php) to display success message or handle the uploaded file:
<!-- upload_success.php -->
<h3>File uploaded successfully!</h3>
<ul>
<?php foreach ($upload_data as $item => $value): ?>
<li><?php echo $item; ?>: <?php echo $value; ?></li>
<?php endforeach; ?>
</ul>
<p><?php echo anchor('upload', 'Upload Another File!'); ?></p>
6. Test Your File Upload:
Access the upload form through the browser and test file uploads.

Comments