Rectangle 27 11

File Uploading with CodeIgniter

It seems the problem is you send the form request to welcome/do_upload, and call the Welcome::do_upload() method in another one by $this->do_upload().

$_FILES
var_dump($data['upload_data']);
NULL
welcome/second_method
$this->do_upload();

Then change the form helper function (within the View) as follows1:

// Change the 'second_method' to your method name
echo form_open_multipart('welcome/second_method');

CodeIgniter has documented the Uploading process very well, by using the File Uploading library.

You could take a look at the sample code in the user guide; And also, in order to get a better understanding of the uploading configs, Check the Config items Explanation section at the end of the manual page.

Also there are couple of articles/samples about the file uploading in CodeIgniter, you might want to consider:

Just as a side-note: Make sure that you've loaded the url and form helper functions before using the CodeIgniter sample code:

// Load the helper files within the Controller
$this->load->helper('form');
$this->load->helper('url');
form_open_multipart()
<form method="post" action="controller/method" enctype="multipart/form-data" />

I stumbled on this Q&A from a Google search for another question. You may want to update your answer with the following link codeigniter.com/userguide3/libraries/ as the ellislab.com/codeigniter/user-guide/libraries/ library is out of date.

How to upload image in CodeIgniter? - Stack Overflow

codeigniter file-upload
Rectangle 27 2

<html>
<body>
<form method="POST" action="<?php echo site_url('my-controller/file_upload');?>" 'enctype'=>'multipart/form-data'>
<label for="file">Filename:</label>
<input type="file" name="userfile[]" id="file" multiple>
<input type="submit" value="upload"></form>
</body>
</html>

and in your controller make a function

$files = $_FILES;
                $cpt = count($_FILES['userfile']['name']);
                 for($i=0; $i<$cpt; $i++)
                {
                $_FILES['userfile']['name']= $files['userfile']['name'][$i];
                $_FILES['userfile']['type']= $files['userfile']['type'][$i];
                $_FILES['userfile']['tmp_name']= $files['userfile']['tmp_name'][$i];
                 $_FILES['userfile']['error']= $files['userfile']['error'][$i];
                 $_FILES['userfile']['size']= $files['userfile']['size'][$i];
                $this->upload->initialize($this->set_upload_options());
                $this->upload->do_upload();
                $fileName = $_FILES['userfile']['name'];
                 $images[] = $fileName;

php - How to upload multiple files in CodeIgniter? - Stack Overflow

php codeigniter upload multifile-uploader
Rectangle 27 24

If you're using Codeigniter version 2.1.0 there is a bug in the Upload library. See http://codeigniter.com/forums/viewthread/204725/ for more details.

Basically what I did was modify a few lines of code in the File Upload Class (Location: ./system/libraries/Upload.php)

$this->file_type = @mime_content_type($file['tmp_name']);
if (strlen($this->file_type) > 0) return;
@exec('file --brief --mime-type ' . escapeshellarg($file['tmp_name']), $output, $return_code);

As you can probably see, line 1058 tries to use an array value that does not exist.

helped a lot ... :)

php - Uploading in Codeigniter - The filetype you are attempting to up...

php codeigniter
Rectangle 27 20

You can Upload any number of Files..

$config['upload_path'] = 'upload/Main_category_product/';
$path=$config['upload_path'];
$config['allowed_types'] = 'gif|jpg|jpeg|png';
$config['max_size'] = '1024';
$config['max_width'] = '1920';
$config['max_height'] = '1280';
$this->load->library('upload', $config);

foreach ($_FILES as $fieldname => $fileObject)  //fieldname is the form field name
{
    if (!empty($fileObject['name']))
    {
        $this->upload->initialize($config);
        if (!$this->upload->do_upload($fieldname))
        {
            $errors = $this->upload->display_errors();
            flashMsg($errors);
        }
        else
        {
             // Code After Files Upload Success GOES HERE
        }
    }
}

Is there a setting for the number of files? I was only able to upload 20 with my codeigniter code and its not much different than this.

$this->upload->initialize()

It gave me error is_uploaded_file() expects parameter 1 to be string, array given, as I tried to debug, $fieldname is an array.

I tried your code I get one issue with this code. If user upload text file or any other nonimage file with the images (textfile + images) then it uploads some of them and returns the error of file type. Ideally, it may not allow any single image if one of them is not an image. Any help over this? @srbhbarot

@jason I can only upload a max of 20 files, too. Would like a solution.

php - Upload multiple files in CodeIgniter - Stack Overflow

php codeigniter file-upload
Rectangle 27 22

Parameter to $this->upload->do_upload() function should be the name of the form field. (If you call it without parameters userfile would be used). It seems in your case it should be 'image'. Instead of:

$image1=$this->input->post('image');
$image1='image';

Thanks alot for that... but now the image value doesn't pass file_name. i get "Column 'image' cannot be null". Is "'image' => $mage['file_name']" the correct way to pass the file name?

No i assumed that 'image' was the name of the form element. you should name the form element like: <input type="file" name="image" /> or if you want the default value for do_upload <input type="file" name="userfile" />

php - "did not select a file to upload" when uploading using codeignit...

php codeigniter file-upload
Rectangle 27 8

I ran into this problem aswell. The $_FILES data is sent a diffent structure (due to the multiple="" attribute) so codeigniter can't handle it. Prepend this before the uploading process:

$arr_files  =   @$_FILES['userfile'];

$_FILES     =   array();
foreach(array_keys($arr_files['name']) as $h)
$_FILES["file_{$h}"]    =   array(  'name'      =>  $arr_files['name'][$h],
                                    'type'      =>  $arr_files['type'][$h],
                                    'tmp_name'  =>  $arr_files['tmp_name'][$h],
                                    'error'     =>  $arr_files['error'][$h],
                                    'size'      =>  $arr_files['size'][$h]);

Then in the loop function use this:

$this->load->library('upload');

$arr_config =   array(  'allowed_types' =>  'gif|jpg|png',
                            'upload_path'   =>  'url_path/');

foreach(array_keys($_FILES) as $h) {

    // Initiate config on upload library etc.

    $this->upload->initialize($arr_config);

    if ($this->upload->do_upload($h)) {

        $arr_file_data  =   $this->upload->data();

    }

}

Explanation: I simply change the structure of $_FILES to the common structure which is sent on a default <input type="file" /> and the run a loop, fetching all their key names.

how can i get a var_dump() on the uploaded data before i proceed

You want information about the $_FILES data or the data which is created upon uploading with Codeigniter?

problem about the data has been solved. now i just want to the loop i should use to extract the info from the array.(provided in the update)

I can't tell exactly what you're after. I've updated the last code to hopefully make it clearer. You still need to change the structure of your $_FILES array before uploading this.

php - Codeigniter & HTML5 - Trying to Upload Multiple Images at Once -...

php codeigniter file-upload codeigniter-2
Rectangle 27 20

images[]
private function upload_files($path, $title, $files)
    {
        $config = array(
            'upload_path'   => $path,
            'allowed_types' => 'jpg|gif|png',
            'overwrite'     => 1,                       
        );

        $this->load->library('upload', $config);

        $images = array();

        foreach ($files['name'] as $key => $image) {
            $_FILES['images[]']['name']= $files['name'][$key];
            $_FILES['images[]']['type']= $files['type'][$key];
            $_FILES['images[]']['tmp_name']= $files['tmp_name'][$key];
            $_FILES['images[]']['error']= $files['error'][$key];
            $_FILES['images[]']['size']= $files['size'][$key];

            $fileName = $title .'_'. $image;

            $images[] = $fileName;

            $config['file_name'] = $fileName;

            $this->upload->initialize($config);

            if ($this->upload->do_upload('images[]')) {
                $this->upload->data();
            } else {
                return false;
            }
        }

        return $images;
    }

ok , what kind of file is .fr3 files? pdf is application, html is text, fr3 is?

php - Multiple files upload in Codeigniter - Stack Overflow

php codeigniter file-upload upload
Rectangle 27 20

images[]
private function upload_files($path, $title, $files)
    {
        $config = array(
            'upload_path'   => $path,
            'allowed_types' => 'jpg|gif|png',
            'overwrite'     => 1,                       
        );

        $this->load->library('upload', $config);

        $images = array();

        foreach ($files['name'] as $key => $image) {
            $_FILES['images[]']['name']= $files['name'][$key];
            $_FILES['images[]']['type']= $files['type'][$key];
            $_FILES['images[]']['tmp_name']= $files['tmp_name'][$key];
            $_FILES['images[]']['error']= $files['error'][$key];
            $_FILES['images[]']['size']= $files['size'][$key];

            $fileName = $title .'_'. $image;

            $images[] = $fileName;

            $config['file_name'] = $fileName;

            $this->upload->initialize($config);

            if ($this->upload->do_upload('images[]')) {
                $this->upload->data();
            } else {
                return false;
            }
        }

        return $images;
    }

ok , what kind of file is .fr3 files? pdf is application, html is text, fr3 is?

php - Multiple files upload in Codeigniter - Stack Overflow

php codeigniter file-upload upload
Rectangle 27 2

This is an extension of the CI_Upload class that I modified to upload multiple files, just copy this to the MY_Upload.php file. It also makes the directory as well.

Then all you need to do in the controller function is arrange your files into the an array, where the name of the field and the key are the array keys and the config is the data. In you case something like this:

$project_files['files'][0] = array(
            'upload_path' => './uploads/'.$projectName.'/',
            'max_size' => 0,
            'allowed_types' => 'xml|etl',
            'overwrite' => TRUE,
            'remove_spaces' => TRUE,
        );
$project_files['files'][1] = array(
            'upload_path' => './uploads/'.$projectName.'/',
            'max_size' => 0,
            'allowed_types' => 'xml|etl',
            'overwrite' => TRUE,
            'remove_spaces' => TRUE,
        );

IF all the files configs are the same just make a for loop to set this up, it will also take 'named keys', ie. $project_files['files']['file_key'].

if($this->upload->upload_files($project_files)){/*all files uploaded successfully*/}

php - Upload multiple files in CodeIgniter - Stack Overflow

php codeigniter file-upload
Rectangle 27 2

I had the same problem. and i solved by modifying the mime for xls

'xls'   =>  array('application/excel', 'application/vnd.ms-excel', 'application/msexcel'),
array('application/excel', 'application/vnd.ms-excel', 'application/octet-stream'),

php - xls file is not uploading in codeigniter? - Stack Overflow

php codeigniter file-upload csv xls
Rectangle 27 2

When using the upload library with these config values:

$config['upload_path'] = 'uploads/';
$config['allowed_types'] = 'wav';
$config['max_size'] = '1000000';
$this->load->library('upload', $config).

If you attempt to upload a .wav file (tested in firefox 7.0.1). It will report an error of 'The filetype you are attempting to upload is not allowed.'.

This can be solved by replacing line 68 in application/config/mimes.php

'wav' => 'audio/x-wav'
 with:
'wav' => array('audio/wav', 'audio/wave', 'audio/x-wav'),
$this->_file_mime_type($_FILES[$field]); var_dump($this->file_type); die();

Then do upload your .wmv file. It would show something like application/octet-stream or whatever. Add that to your mimes.php.

I have already do that. but get the same error

Please check the updated answer.

it's work like a charm.

Can you please send me the error which you get.

php - File upload in Codeigniter 3 - Stack Overflow

php codeigniter upload wav
Rectangle 27 4

you have to use below code to upload files. You are missing multipart attribute in your form.

echo form_open_multipart('/Home/upload');

php - You did not select a file to upload CodeIgniter - Stack Overflow

php codeigniter upload
Rectangle 27 1

For multiple files you have some alternatives, you can create each field as a user press a button or use the multiple propriety to <input> tag.

To manage this multiple uploads you must create your own upload library reading each $_FILES['nameoffield'] in a foreach loop for example although there are alternatives ready to be used like: https://github.com/nicdev/CodeIgniter-Multiple-File-Upload

On your database, you could have two fields that stores the original file name and path, and the encrypted one. Probably associated to a random unique number or timestamp.

To email encrypted link, and by encrypted I think you are saying a disguised link to the file, not using original name, you simple select the field which store the encrypted name to a controller, like download and keep a variable to receive a value as parameter. This value you must check on database if it really exists and then redirect to the file. By doing that you should have your file being downloaded.

how about to have different random link, every time a user download the file through website or email encrypted link? I don't know how to do that.. :( Thank you very much! I really appreciate it. :)

function file_upload(){         $this->load->library('upload', $config);          if(!$this->upload->do_upload()){             $error = array('error' => $this->upload->display_errors());             $this->load->view('gallery/gallery', $error);         }         else{             $data = array('upload_data' => $this->upload->data());             $this->load->view('gallery/upload_success', $data);         }

php - Codeigniter - Download a upload file in the directory - Stack Ov...

php codeigniter email file-upload download
Rectangle 27 94

function do_upload()
{       
    $this->load->library('upload');

    $files = $_FILES;
    $cpt = count($_FILES['userfile']['name']);
    for($i=0; $i<$cpt; $i++)
    {           
        $_FILES['userfile']['name']= $files['userfile']['name'][$i];
        $_FILES['userfile']['type']= $files['userfile']['type'][$i];
        $_FILES['userfile']['tmp_name']= $files['userfile']['tmp_name'][$i];
        $_FILES['userfile']['error']= $files['userfile']['error'][$i];
        $_FILES['userfile']['size']= $files['userfile']['size'][$i];    

        $this->upload->initialize($this->set_upload_options());
        $this->upload->do_upload();
    }
}

private function set_upload_options()
{   
    //upload an image options
    $config = array();
    $config['upload_path'] = './Images/';
    $config['allowed_types'] = 'gif|jpg|png';
    $config['max_size']      = '0';
    $config['overwrite']     = FALSE;

    return $config;
}

CinetiK, if our help was useful (you have found the solution through my answer) you must mark our answer is useful!! The solution is in my answer!!

Works for me. is there any way to make a table of all the selected files?

This code is also the only way I can get it to work. However it's so ugly that one need to convert the array values... Should be a more beautiful solution! Possibly extending the ul library?

Multiple files upload (Array) with CodeIgniter 2.0 - Stack Overflow

arrays file codeigniter upload
Rectangle 27 4

I've had these same problems with CI and haven't been able to find a fix on the forums or via google. What I've done is to allow all filetypes, so that the file gets uploaded. Then, I handle the logic manually to determine whether to allow/keep the file, or delete it and tell the user that filetype is not allowed.

$config['upload_path'] = './uploads/invoices/';
$config['allowed_types'] = '*'; // add the asterisk instead of extensions
$config['max_size'] = '3000';
$this->load->library('upload', $config);

if (!$this->upload->do_upload('proof_of_purchase'))
{
    $data['error'] = $this->upload->display_errors();
    $data['include'] = 'pages/classic-register';
} else {
    $data['upload_data'] = $this->upload->data();
    // use custom function to determine if filetype is allowed
    if (allow_file_type($data['upload_data']['file_ext'])) 
    {
        $filename = $data['upload_data']['file_name'];
    }
    else
    {
        show_error('File type is not allowed!');
    }
}

Until I find something that works, this is the only solution that works for me at present. Tried modifying config/mimes.php and system/libraries/Upload.php, to no avail. I guess I can post-process file types to make sure they are legitimate types.

php - Uploading in Codeigniter - The filetype you are attempting to up...

php codeigniter
Rectangle 27 1

public function save() {
  $data = array();

  $config['upload_path'] = './uploads/';
  $config['allowed_types'] = 'jpg|png';
  $config['max_size'] = 5024;
  $config['encrypt_name'] = true;  

  $this->load->library('upload', $config);

  $data['pr_name'] = $this->input->post('pr_name');
  $data['pr_code'] = $this->input->post('pr_code');

  if (!$this->upload->do_upload('userfile')) {
    $error = array('error' => $this->upload->display_errors());
  } else {
    $fileData = $this->upload->data();
    $data['userfile'] = $fileData['file_name'];
  }

  if (!$this->upload->do_upload('userfile2')) {
    $error = array('error' => $this->upload->display_errors()); 
  } else {
    $fileData = $this->upload->data();
    $data['userfile2'] = $fileData['file_name'];
  }
  // Verify the data using print_r($data); die;
  $result = $this->Product_model->addProducts($data);
  if ($result) {
    $this->load->view('success_view');
  } else {
    $this->load->view('failure_view');
  }
}

WOW it really worked, I can't thank you enough. You are a life saver

file - How to upload two images into two fields using codeigniter - St...

codeigniter file upload
Rectangle 27 6

enctype="multipart/form-data"
<form action='' method=''enctype="multipart/form-data>
<input type='file' name='field_name'/>

and in controller upload code should be $this->upload->do_upload("field_name") and jsut check whether file reaches in server side by making just print like

print_r($_FILES);

if you get null array then make sure that client side code is correct.

php - "did not select a file to upload" when uploading using codeignit...

php codeigniter file-upload
Rectangle 27 1

Now when I upload 2 files the first file is correctly resized. With the second file I get the error: Your server does not support the GD function required to process this type of image. But the 2 images I tried to upload are the same...

You are reloading the library each time in the loop. As I said, try unloading it at the end, so it is not loading multiple times.

php - Multiple file upload and resize in codeigniter - Stack Overflow

php image codeigniter upload image-resizing
Rectangle 27 1

/**
 * @param array $config
 * @param string $file_input_name
 * @param array $resize_configs
 * @return array
 * */
protected function multiple_upload($config = array(),$file_input_name,$resize_configs = null)
{
    $fileNames = array();

    $conf['upload_path'] = FCPATH . 'assets/img';
    $conf['allowed_types'] = 'jpg|png|jpeg';
    $conf['max_size'] = 50000;
    $conf['max_width'] = 3600;
    $conf['max_height'] = 1800;
    $conf['maintain_ratio'] = TRUE;
    $conf['encrypt_name'] = TRUE;

    foreach ($config as $item => $val){
        $conf[$item] = $val;
    }

    $this->load->library('upload',$conf);
    $this->load->library('image_lib');
    $files = $_FILES;
    $cpt = sizeof($_FILES[$file_input_name]['name']);
    for($i = 0; $i < $cpt; $i++)
    {
        $_FILES['userfile']['name']     = $files[$file_input_name]['name'][$i];
        $_FILES['userfile']['type']     = $files[$file_input_name]['type'][$i];
        $_FILES['userfile']['tmp_name'] = $files[$file_input_name]['tmp_name'][$i];
        $_FILES['userfile']['error']    = $files[$file_input_name]['error'][$i];
        $_FILES['userfile']['size']     = $files[$file_input_name]['size'][$i];

        if($this->upload->do_upload()){
            $fileNames[] = $this->upload->file_name;
            if(!is_null($resize_configs)){
                //Image Resizing
                $img_config['source_image'] = $this->upload->upload_path.$this->upload->file_name;
                foreach($resize_configs as $key => $value){
                    $img_config[$key] = $value;
                }

                $this->image_lib->initialize($img_config);
                $this->image_lib->resize();
            }
        }
    }

    return $fileNames;

}

what kind of validation you need?

for file input which one given in question like for song_name[] its working for song_name but not for song_name[]

php - upload multiple file in Codeigniter - Stack Overflow

php codeigniter file-upload
Rectangle 27 1

I've also tried a "for" loop in which I iterate through the code and it kind of works, but it uploads the last image as many times as images were being uploaded.

It looks like you attempted to fix the problem with a for loop which was only broken because you have the incorrect naming convention for the HTML form.

<form action="upload.php" method="post" enctype="multipart/form-data">
    <input type="file" name="car_1" value="" />
    <input type="file" name="car_2" value="" />
    <input type="file" name="car_3" value="" />
    </form>

Then in your code you can change

$uploadimages = $this->upload->do_upload('car_1');

You should be able to enclose it in a loop to go through each image you want uploaded with the afor mentioned for loop you were using

Thank you very much ChrisK, you helped me realize that I was not as lost as I thought, and also the problem I was having was that inside the loop I had a "$i++" when it should have been just "$i". That was messing up my order/sequence I guess. Again, Thanks a lot. it is working now.

Glad to have helped

php - Multiple file upload with codeigniter - Stack Overflow

php codeigniter file-upload