HTML 5 PHP CodeIgniter Upload

Hi there! As I am working on a certain project (the Metacritic API is suspended due to a project from my office) I need to create a feature in uploading multiple files. Well, I hate to use jQ multiple upload or creating many fields to upload many files. Thank God there is HTML 5! This post contains the combination of HTML 5 multiple upload and processing using PHP Codeigniter.

So let’s make it simple!

First we have to make the view. The view will mainly contains upload field. In this example I will create two fields. The one that have multiple attribute and the one that don’t.

 <!--?php echo form_upload('img', ''); ?--></div>
 <!--?php echo form_upload('gallery[]', '', 'multiple=""'); ?--></div>

Second, let’s focus on the background process. There is a reason why I put two fields there (the one with multiple and the one without). I want to make the process can manage different situations. So here is the code.

$pathtoDB ='assets/images/' . date("YmdHis"); // create a folder with unique name

$this->load->library('upload'); // remember to load the library outside the loop


foreach ($_FILES as $key => $value) {
    $total_count_of_files = count($_FILES[$key]['name']);
    for($i=0; $i<$total_count_of_files; $i++)     {         if ($total_count_of_files >= 1 && is_array($_FILES[$key]['name'])){ // this part will process the files if they are from multiple field
            $_FILES['file']['name'] = $_FILES[$key]['name'][$i];
            $_FILES['file']['type'] = $_FILES[$key]['type'][$i];
            $_FILES['file']['tmp_name'] = $_FILES[$key]['tmp_name'][$i];
            $_FILES['file']['error'] = $_FILES[$key]['error'][$i];
            $_FILES['file']['size'] = $_FILES[$key]['size'][$i];
            $_FILES['file'] = $_FILES[$key]; // this part will process the file from single field

        $config['allowed_types'] = 'gif|jpg|jpeg|png';
        $config['upload_path'] = $pathtoDB;
        $config['max_size'] = '0';
        $config['overwrite'] = FALSE;
        if (!$this->upload->do_upload()) // Here I did not refer to a certain field to upload
            $uploaded_info[]  =  array('error_msg' => $this->upload->display_errors());

You can place the second code chunk on your controller.

That’s all. Simple and clear I think. 😀 Feel free to comment.

UPDATE: I made a little change to the code above on line 13. It now handles if the multiple upload field only contains one file selected (not many)