prakashchhetri prakashchhetri - 4 months ago 20
PHP Question

Codeigniter multiple images upload, get each filename

I am using the code below to handle image upload. Every thing is going fine. I have allowed the option to upload two images, one will be the logo and another the screenshot.

Now when I am providing the option to edit the uploads, say choose new files to upload and replace the old ones, I am having this problem.

In my

images[]
array, I will get the image names one by one with the help of loop. However when the user wants to change the second image(screenshot) and selects nothing in the logo field, only screenshot should be changed.

But in the
images[]
array, the first element will be the first from the uploads. If i select both the images it is all right, I will get logo.jpg in
images[0]
and screenshot.jpg in
images[1]
. But when I select only the second image, i will get screenshot.jpg in
images[0]
. However, the first element of the array should be blank and the second element of the array should have the data of the second image upload option so the the changes to take into effect. How can i acheive that?

$config['upload_path'] = '../uploads/';
$config['allowed_types'] = '*';
$config['max_size'] = '0';
$config['max_width'] = '0';
$config['max_height'] = '0';

$this->load->library('upload', $config);
$image = array();
foreach ($_FILES as $key => $value) {

if (!empty($value['tmp_name'])) {

if ( ! $this->upload->do_upload($key)) {
$error = array('error' => $this->upload->display_errors());
//failed display the errors
} else {
//success
$data = $this->upload->data();
$image[]= $data['file_name'];
}

}
}

Answer

Remember, You must to initialize the upload library with each upload.

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

User guide: http://ellislab.com/codeigniter/user-guide/libraries/file_uploading.html

Edit:

You can check the $_FILES array and check if there are the name of the screenshot input and the logo input, if they aren´t, you can create the array you need

I´ve found this:

A simpler way to have create that data structure is to name your HTML file inputs different names. >If you want to upload multiple files, use:

<input type=file name=file1>
<input type=file name=file2>
<input type=file name=file3>

Each field name will be a key in the $_FILES array.

http://www.php.net/manual/es/features.file-upload.multiple.php#53933