Skip to main content

Multiple files upload in CodeIgniter.

Create an HTML form to select multiple images at once.
Upload images to the server using CodeIgniter’s Upload library.
Store file data in the MySQL database.
Retrieve images from the database and display on the web page.

Create Database Table
To store the file name and related information, a table needs to be created in the database. The following SQL creates a files table in the MySQL database.

CREATE TABLE `files` (
 `id` int(11) NOT NULL AUTO_INCREMENT,
 `file_name` varchar(255) COLLATE utf8_unicode_ci NOT NULL,
 `uploaded_on` datetime NOT NULL,
 `status` enum('1','0') COLLATE utf8_unicode_ci NOT NULL DEFAULT '1' COMMENT '1=Active, 0=Inactive',
 PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;

Create File Upload Folder
Create a directory on the server where you want to store the uploaded files. For example, create a uploads/files/ directory in the root folder of the application.


Controller (Upload_files.php)
The Upload_Files controller contains 2 functions, __construct() and index().

__construct() –
Loads SESSION library to show the uploading status to user.
Loads File model that helps to insert file data into the database and get files data from the database.
index() – This function handles the multiple file upload functionality.
Set preferences (upload path, allowed types, etc) and initialize Upload library.
Upload images to the server using Upload library.
Insert images data in the database using File model.
Get all images data from the database.
Pass the data to the view.
<?php defined('BASEPATH') OR exit('No direct script access allowed');

class Upload_Files extends CI_Controller {
    function  __construct() {
        parent::__construct();
        // Load session library
        $this->load->library('session');
       
        // Load file model
        $this->load->model('file');
    }
   
    function index(){
        $data = array();
        // If file upload form submitted
        if($this->input->post('fileSubmit') && !empty($_FILES['files']['name'])){
            $filesCount = count($_FILES['files']['name']);
            for($i = 0; $i < $filesCount; $i++){
                $_FILES['file']['name']     = $_FILES['files']['name'][$i];
                $_FILES['file']['type']     = $_FILES['files']['type'][$i];
                $_FILES['file']['tmp_name'] = $_FILES['files']['tmp_name'][$i];
                $_FILES['file']['error']     = $_FILES['files']['error'][$i];
                $_FILES['file']['size']     = $_FILES['files']['size'][$i];
               
                // File upload configuration
                $uploadPath = 'uploads/files/';
                $config['upload_path'] = $uploadPath;
                $config['allowed_types'] = 'jpg|jpeg|png|gif';
               
                // Load and initialize upload library
                $this->load->library('upload', $config);
                $this->upload->initialize($config);
               
                // Upload file to server
                if($this->upload->do_upload('file')){
                    // Uploaded file data
                    $fileData = $this->upload->data();
                    $uploadData[$i]['file_name'] = $fileData['file_name'];
                    $uploadData[$i]['uploaded_on'] = date("Y-m-d H:i:s");
                }
            }
           
            if(!empty($uploadData)){
                // Insert files data into the database
                $insert = $this->file->insert($uploadData);
               
                // Upload status message
                $statusMsg = $insert?'Files uploaded successfully.':'Some problem occurred, please try again.';
                $this->session->set_flashdata('statusMsg',$statusMsg);
            }
        }
       
        // Get files data from the database
        $data['files'] = $this->file->getRows();
       
        // Pass the files data to view
        $this->load->view('upload_files/index', $data);
    }

}


Model (File.php)
The File model contains 3 functions, __construct(), getRows() and insert().

__construct() – Define table name where the files data will be stored.
getRows() – Fetch the file data from the files table of the database. Returns a single record if ID is specified, otherwise all records.
insert() – Insert multiple files data into the database using insert_batch() function of Query Builder Class.
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class File extends CI_Model{
    function __construct() {
        $this->tableName = 'files';
    }
   
    /*
     * Fetch files data from the database
     * @param id returns a single record if specified, otherwise all records
     */
    public function getRows($id = ''){
        $this->db->select('id,file_name,uploaded_on');
        $this->db->from('files');
        if($id){
            $this->db->where('id',$id);
            $query = $this->db->get();
            $result = $query->row_array();
        }else{
            $this->db->order_by('uploaded_on','desc');
            $query = $this->db->get();
            $result = $query->result_array();
        }
        return !empty($result)?$result:false;
    }
   
    /*
     * Insert file data into the database
     * @param array the data for inserting into the table
     */
    public function insert($data = array()){
        $insert = $this->db->insert_batch('files',$data);
        return $insert?true:false;
    }
   
}

View (upload_files/index.php)
Initially, an HTML form is displayed with file input to select multiple files. After the form submission, the data is posted to index() function of Upload_Files controller for uploading multiple images to the server.

<!-- display status message -->
<p><?php echo $this->session->flashdata('statusMsg'); ?></p>

<!-- file upload form -->
<form method="post" action="" enctype="multipart/form-data">
    <div class="form-group">
        <label>Choose Files</label>
        <input type="file" name="files[]" multiple/>
    </div>
    <div class="form-group">
        <input type="submit" name="fileSubmit" value="UPLOAD"/>
    </div>
</form>

Under the file upload form, the uploaded images names and retrieved from the database and display the respective images from the server in a gallery view.

<!-- display uploaded images -->
<div class="row">
    <ul class="gallery">
        <?php if(!empty($files)){ foreach($files as $file){ ?>
        <li class="item">
            <img src="<?php echo base_url('uploads/files/'.$file['file_name']); ?>" >
            <p>Uploaded On <?php echo date("j M Y",strtotime($file['uploaded_on'])); ?></p>
        </li>
        <?php } }else{ ?>
        <p>Image(s) not found.....</p>
        <?php } ?>
    </ul>
</div>

Upload Class Preferences
In the example, some basic preferences are used for Upload library configuration ($config). But you can specify various preferences provided by the Upload Class in CodeIgniter.

upload_path – The path of the directory where the file will be uploaded. The path must be absolute and directory must be writable.
allowed_types – The mime types of the file that allows being uploaded.
file_name – If specified, the uploaded file will be renamed with this name.
file_ext_tolower – (TRUE/FALSE) If set to TRUE, file extension will be lower case.
overwrite – (TRUE/FALSE) TRUE – If a file exists with the same name, it will be overwritten. FALSE – If a file exists with the same name, a number will append to the filename.
max_size – (in kilobytes) The maximum size of the file that allowed to upload. Set to 0 for no limit.
max_width – (in pixels) The maximum width of the image that allowed to upload. Set to 0 for no limit.
max_height – (in pixels) The maximum height of the image that allowed to upload. Set to 0 for no limit.
min_width – (in pixels) The minimum width of the image that allowed to upload. Set to 0 for no limit.
min_height – (in pixels) The minimum height of the image that allowed to upload. Set to 0 for no limit.
max_filename – The maximum length of the file name. Set to 0 for no limit.

Comments

Popular posts from this blog

SETUP REST API IN CI

1. Create Rest_controller.php inside controllers and paste code: <?php defined('BASEPATH') OR exit('No direct script access allowed'); require APPPATH . '/libraries/API_Controller.php'; class Rest_controller extends API_Controller { public function __construct() { parent::__construct(); } public function index() { $this->api_return(             [ 'status' => true,                'result' => "Welcome to Testservices."             ],         200); } } ?> 2. Create api.php inside config and paste code : <?php defined('BASEPATH') OR exit('No direct script access allowed'); /**  * API Key Header Name  */ $config['api_key_header_name'] = 'X-API-KEY'; /**  * API Key GET Request Parameter Name  */ $config['api_key_get_name'] = 'key'; /**  * API Key POST Request Parameter Name ...

NGrok Setup

 https://dashboard.ngrok.com/get-started/setup 1. Unzip to install On Linux or Mac OS X you can unzip ngrok from a terminal with the following command. On Windows, just double click ngrok.zip to extract it. unzip /path/to/ngrok.zip 2. Connect your account Running this command will add your authtoken to the default ngrok.yml configuration file. This will grant you access to more features and longer session times. Running tunnels will be listed on the endpoints page of the dashboard. ngrok config add-authtoken 1woFn9zVqcI4VeGuSIiN2VtmnPa_ZXuAuF1AAPkqApr7WVsQ 3. Fire it up Read the documentation on how to use ngrok. Try it out by running it from the command line: ngrok help To start a HTTP tunnel forwarding to your local port 80, run this next: ngrok http 80

API ( service ) Image or Video Upload

## SAVE  VIDEO public function uploadmedia() { $target_path = "assets/uploads/"; $target_path = $target_path . basename($_FILES['file']['name']); if(move_uploaded_file($_FILES['file']['tmp_name'], $target_path)) { $this->api_return( [ 'status' => true,    'result' => 'uploaded success' ], 200); } else{ $this->api_return( [ 'status' => false,    'result' => 'failed' ], 20); } } ## SAVE FILE IMAGE OR VIDEO public function savefile() { $filetype = $_FILES['file']['type']; if (strpos($filetype, 'image') !== false) { $type = 'image'; } if (strpos($filetype, 'video') !== false) { $type = 'video'; }         $filename = trim($_FILES['file']['name']); // $userid = trim($this->input->get('userid'));...