go to the root of the CI installation and create a folder named “upload”.
Go to the view folder (located at the root of the CI installation) and create a new “file_upload.php” file.
Create a file in the Controller folder
Now the next step is the creation of a php file in the controller folder. Name the file uploadController.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'] = 'upload';
$config['allowed_types'] = 'gif|jpg|png|jpeg';
$config['remove_spaces'] = FALSE;
As you could see, through this function, you could easily restrict the upload path, allowed file types and dimensions of the image.
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'));
Now open “file_upload.php" file from view folder and add the following code to it:
<html>
<head>
<title>Image or file upload in codeigniter</title>
</head>
<body>
<form action="<?php echo base_url('uploadController/upload_image') ?>" method="post" enctype="multipart/form-data">
<div>
<label>Upload image:</label>
<input type="file" name="img" />
<button type="submit" id="submit" name="submit">Upload</button>
</div>
</form>
<body>
</html>
Now open uploadController.php" file from controller folder and add the following code to it:
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class uploadController extends CI_Controller {
public function __construct() {
parent::__construct();
$this->load->helper(array('form', 'url'));
$this->load->library('upload');
}
public function index(){
$this->load->view('file_upload');
}
public function upload_image($filename){
if ($_FILES['image']['name'] != "") {
$filename = $_FILES['image']['name'];
$result = $this->do_upload($filename);
if($result){
echo 'File uploaded successfully.';
}else{
echo 'Error in file upload.';
}
}
}
public function do_upload($filename){
$config['upload_path'] = 'assets_signi/upload/blog/';
$config['file_name'] = $filename;
$config['allowed_types'] = 'gif|jpg|png|jpeg';
$config['remove_spaces'] = FALSE;
$this->load->library('upload', $config);
if (!$this->upload->do_upload('file')) {
return FALSE;
} else {
return TRUE;
}
}
?>