CodeIgniter file uploading class
We can upload files very simple CodeIgniter File Uploading Class permits files to be uploaded. You can set different preferences,
restricting the file type and size of the files.
Follow this step :-
- Create The Upload form in HTML And save .php Extension
- Create The Controller in Codeigniter
- Create The Upload Directory
Using any text editor, create a form called uploads-form.php. In it place this code and save it to your application/views/ Directory :-
Add the following code to uploads-form.php
<html>
<head>
<title>Upload Form Stack Overlode</title>
</head>
<body>
<?= form_open_multipart('imageupload/do_upload');?> <input type="file" name="userfile" size="20" />
<br /><br />
<input type="submit" value="upload" />
</form>
<?= form_close() ?>
</html>
Create a controller application/controllers/Imageupload.php ,The controllers name must start with uppercase letter but we need to write lowercase letter when we call that controller by URI
And Add the following code to Imageupload.php
<?php defined('BASEPATH') OR exit('No direct script access allowed');
class Imageupload 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/';
$config['allowed_types'] = 'gif|jpg|png';
$config['max_size'] = '';
$config['max_width'] = '';
$config['max_height'] = '';
$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);
}
}
}
Preferences
The following preferences are available on file upload . The default value indicates what will be used if you do not specify that preference file upload.
Preference | Default Value | Options | Description |
---|---|---|---|
upload_path | None | None | The path to the directory where the upload file should be placed. The directory must be permission writable and the path can be absolute or relative. |
allowed_types | None | None | The mime types corresponding to the types of files you allow to be uploaded. Usually the file extension can be used as the mime type. Can be either an array or a pipe-separated string. Ex: jpg|png|gif |
file_name | None | Desired file name | The extension provided in the file name must also be an allowed file type. If no extension is provided in the original file name will be used. |