In this tutorial, we will learn "How to upload multiple files with the help of Codeigniter's customized upload class named as CI_Upload_Multiple in the file named Upload_Multiple.php in the Codeigniter's library". With the help of this library class, we will be able to upload all the files. To see the example of how to upload a single file using the Codeigniter's library class upload click the link below:
Here we will create a “Controller” and a “View”. We will not be dealing with the model and database in this blog. We just want to get the request from the View regarding the files that we want to upload and process the requested data in the Controller and then we will render the information of the upload file which we can also save in the database with the help of SQL queries.
Now we will go through the following steps to upload multiple files:-
Step 1: Let's create a View with name say upload_view.php under the directory “exampleupload/application/views/. This page will display form that will have an option to upload multiple files. Here we are going to upload 3 images of different types.
<html>
<head>
<title>Upload Multiple Files</title>
</head>
<body>
<?php echo $error;?> <!-- Here the error message will be displayed -->
<?php echo form_open_multipart('upload/demo');?>
<?php echo "<input type='file' name='upld_files[]' />"; ?>
<br>
<?php echo "<input type='file' name='upld_files[]' />"; ?>
<br>
<?php echo "<input type='file' name='upld_files[]' />"; ?>
<br>
<?php echo "<input type='submit' name='Submit' value='upload' /> ";?>
<?php echo "</form>"?>
</body>
</html>
Step 2: Create a Controller named “upload”. Now we will write the functions that we will be using to render the “Upload From” page (i.e. upload_view.php) and the action “upload_multiple_file” that will handle the further processing.
public function __construct() {
parent::__construct();
//Below we are using the form helper and url helper
$this->load->helper(array('form', 'url'));
}
public function index(){
$this->load->view('upload/upload_view.php',array('error'=>''));
}
public function upload_multiple_file(){
if($this->input->post('Submit')){
$file_count = count($_FILES['upld_files']['name']);
for($i=0;$i<$file_count;$i++)
{
if($_FILES['upld_files']['name'][$i]!=''){
//upload thumbnail $c
$config = array(
'upload_path' => "./uploads/",
'allowed_types' => 'gif|jpg|jpeg|png',
'index' => $i,
'max_size' => '150',
);
$this->load->library('Upload_Multiple',$config);
if($this->upload_multiple->do_upload($config))
{
$data['fileinfo'][] = array('upload_data' => $this->upload_multiple->data());
}else{
$error = array('error' => $this->upload_multiple->display_errors());
$this->load->view('upload/upload_view', $error);
}
}else{
$error = array('error' => $this->upload_multiple->display_errors());
$this->load->view('upload/upload_view', $error);
}
}
$this->load->view('upload/upload_success',$data);
}
}
Step 3: On successful uploading of the files we can have the display files related information with the help of the view file “upload_success.php”. Though I am not using the database still if anyone who wants to insert the information in the database, can use this information.
<html>
<head>
<title>Upload a file</title>
</head>
<body>
<h3>Your file is uploaded successfully!</h3>
<ul>
<?php foreach ($upload_data as $item => $value):?>
<li><?php echo $item;?>: <?php echo $value;?></li>
<?php endforeach; ?>
</ul>
<p><?php echo anchor('upload/index', 'Click to upload more files..!'); ?></p>
</body>
</html>
Step 4: Now we will add a customized function for uploading multiple files in library class Upload that I renamed to CI_Upload_Multiple in Upload_Multiple.php file and made some changes in the function do_upload.
public function do_upload($config)
{
$field = 'upld_files';
//echo '<pre>';print_r($config);
//echo '<br>';
// Is $_FILES[$field] set? If not, no reason to continue.
if ( ! isset($_FILES[$field]))
{
$this->set_error('upload_no_file_selected');
return FALSE;
}
// Is the upload path valid?
if ( ! $this->validate_upload_path())
{
// errors will already be set by validate_upload_path() so just return FALSE
return FALSE;
}
if(isset($config['index']) && ($config['index'] >= 0)){
// Was the file able to be uploaded? If not, determine the reason why.
if (! is_uploaded_file($_FILES[$field]['tmp_name'][$config['index']]))
{
$error = ( ! isset($_FILES[$field]['error'])) ? 4 : $_FILES[$field]['error'];
//echo 'error number=='.$error.'==Error with the file with name : '.$_FILES[$field]['tmp_name'][$config['index']];die('---fsffasf---');
switch($error)
{
case 1: // UPLOAD_ERR_INI_SIZE
$this->set_error('upload_file_exceeds_limit');
break;
case 2: // UPLOAD_ERR_FORM_SIZE
$this->set_error('upload_file_exceeds_form_limit');
break;
case 3: // UPLOAD_ERR_PARTIAL
$this->set_error('upload_file_partial');
break;
case 4: // UPLOAD_ERR_NO_FILE
$this->set_error('upload_no_file_selected');
break;
case 6: // UPLOAD_ERR_NO_TMP_DIR
$this->set_error('upload_no_temp_directory');
break;
case 7: // UPLOAD_ERR_CANT_WRITE
$this->set_error('upload_unable_to_write_file');
break;
case 8: // UPLOAD_ERR_EXTENSION
$this->set_error('upload_stopped_by_extension');
break;
default : $this->set_error('upload_no_file_selected');
break;
}
return FALSE;
}
// Set the uploaded data as class variables
$this->file_temp = $_FILES[$field]['tmp_name'][$config['index']];
$this->file_size = $_FILES[$field]['size'][$config['index']];
$this->_file_mime_type($_FILES[$field]);
$this->file_type = preg_replace("/^(.+?);.*$/", "\\1", $this->file_type);
$this->file_type = strtolower(trim(stripslashes($this->file_type), '"'));
$this->file_name = $this->_prep_filename($_FILES[$field]['name'][$config['index']]);
$this->file_ext = $this->get_extension($this->file_name);
$this->client_name = $this->file_name;
// Is the file type allowed to be uploaded?
if ( ! $this->is_allowed_filetype())
{ //die('--is_allowed_filetype---');
$this->set_error($this->file_name.' has upload_invalid_filetype error');
return FALSE;
}
// if we're overriding, let's now make sure the new name and type is allowed
if ($this->_file_name_override != '')
{
$this->file_name = $this->_prep_filename($this->_file_name_override);
// If no extension was provided in the file_name config item, use the uploaded one
if (strpos($this->_file_name_override, '.') === FALSE)
{//die('-111--_file_name_override---');
$this->file_name .= $this->file_ext;
}
// An extension was provided, lets have it!
else
{
$this->file_ext = $this->get_extension($this->_file_name_override);
}
if ( ! $this->is_allowed_filetype(TRUE))
{//die('--333-_file_name_override---');
$this->set_error('upload_invalid_filetype');
return FALSE;
}
}
// Convert the file size to kilobytes
if ($this->file_size > 0)
{
$this->file_size = round($this->file_size/1024, 2);
}
// Is the file size within the allowed maximum?
if ( ! $this->is_allowed_filesize())
{
$this->set_error($this->file_name.' has upload_invalid_filesize error');
//return FALSE;
}
// Are the image dimensions within the allowed size?
// Note: This can fail if the server has an open_basdir restriction.
if ( ! $this->is_allowed_dimensions())
{
$this->set_error('upload_invalid_dimensions');
return FALSE;
}
// Sanitize the file name for security
$this->file_name = $this->clean_file_name($this->file_name);
// Truncate the file name if it's too long
if ($this->max_filename > 0)
{
$this->file_name = $this->limit_filename_length($this->file_name, $this->max_filename);
}
// Remove white spaces in the name
if ($this->remove_spaces == TRUE)
{
$this->file_name = preg_replace("/\s+/", "_", $this->file_name);
}
/*
* Validate the file name
* This function appends an number onto the end of
* the file if one with the same name already exists.
* If it returns false there was a problem.
*/
$this->orig_name = $this->file_name;
if ($this->overwrite == FALSE)
{
$this->file_name = $this->set_filename($this->upload_path, $this->file_name);
if ($this->file_name === FALSE)
{
return FALSE;
}
}
/*
* Run the file through the XSS hacking filter
* This helps prevent malicious code from being
* embedded within a file. Scripts can easily
* be disguised as images or other file types.
*/
if ($this->xss_clean)
{
if ($this->do_xss_clean() === FALSE)
{
$this->set_error('upload_unable_to_write_file');
return FALSE;
}
}
/*
* Move the file to the final destination
* To deal with different server configurations
* we'll attempt to use copy() first. If that fails
* we'll use move_uploaded_file(). One of the two should
* reliably work in most environments
*/
if ( ! @copy($this->file_temp, $this->upload_path.$this->file_name))
{
if ( ! @move_uploaded_file($this->file_temp, $this->upload_path.$this->file_name))
{
$this->set_error('upload_destination_error');
return FALSE;
}
}
/*
* Set the finalized image dimensions
* This sets the image width/height (assuming the
* file was an image). We use this information
* in the "data" function.
*/
$this->set_image_properties($this->upload_path.$this->file_name);
return TRUE;
}
}
Step 5: Finally we will create a folder in the root directory of our project. Let say my project folder name is exampleupload. Hence we will create a folder such as “exampleupload/upload”
Now on our browser address bar we will write the following path
1- localhost/exampleupload/upload/index
2- Upload the file
We will get the following output:
Your file is uploaded successfully!
file_name: Audi_A4.jpg
file_type: image/jpeg
file_path: /var/www/html/exampleupload/uploads/
full_path: /var/www/html/exampleupload/uploads/Audi_A4.jpg
raw_name: Audi_A4
orig_name: Audi_A4.jpg
client_name: Audi A4.jpg
file_ext: .jpg
file_size: 263.15
is_image: 1
image_width: 1700
image_height: 1132
image_type: jpeg
image_size_str: width="1700" height="1132"
Your file is uploaded successfully!
file_name: Audi_A4b.jpg
file_type: image/jpeg
file_path: /var/www/html/exampleupload/uploads/
full_path: /var/www/html/exampleupload/uploads/Audi_A4b.jpg
raw_name: Audi_A4b
orig_name: Audi_A4b.jpg
client_name: Audi A4b.jpg
file_ext: .jpg
file_size: 51.22
is_image: 1
image_width: 720
image_height: 449
image_type: jpeg
image_size_str: width="720" height="449"
Your file is uploaded successfully!
file_name: Audi_TT.jpg
file_type: image/jpeg
file_path: /var/www/html/exampleupload/uploads/
full_path: /var/www/html/exampleupload/uploads/Audi_TT.jpg
raw_name: Audi_TT
orig_name: Audi_TT.jpg
client_name: Audi TT.jpg
file_ext: .jpg
file_size: 21
is_image: 1
image_width: 484
image_height: 172
image_type: jpeg
image_size_str: width="484" height="172"
Click to upload more files..!
Note: We will discuss on the failure messages in case of file not uploaded due to specifications miss matched in another blog.
0 Comment(s)