This article mainly introduces the CodeIgniter multiple file upload use examples, need friends can refer to the following
The code is as follows: <?php if (!defined ("BasePath")) {exit ("No Direct script access Allowed");} /** * Multi-uploa D * * Extends codeigniters Native Upload class to add support for multiple * uploads. * * @package codeigniter * @subpackage Libraries * @category uploads / CL Ass My_upload extends Ci_upload { /** * Properties / protected $_multi_upload_data = Array (); Protected $_multi_file_name_override = ""; /** * Initialize preferences * * @access public   ; * @param array * @return void / Public Function Initialize ($config = arr Ay ()) { //upload default settings. $defaults = Array ( & nbsp; " Max_size " => 0, &NBsp "Max_width" => 0, "Max_height" => 0,   ; "Max_filename" => 0, "allowed_types" => "", "file_temp" => "", "file_name" => "", &N Bsp "Orig_name" => "", "File_type" => "", &NB Sp "file_size" => "", "File_ext" => "", &nbs P "Upload_path" => "", "overwrite" => FALSE, "Encrypt_name" => FALSE, "is_image" = > FALSE, "image_width" => "", Image_heigh T "&NBsp;=> ", " Image_type " =>" ", " image_size _str "=>" " " error_msg " => Array (), , " Mim Es " => Array (), " remove_spaces " => TRUE, & nbsp "Xss_clean" => FALSE, "Temp_prefix" => "Temp_file_", &NB Sp "client_name" => "" ( ); //set each configuration. foreach ($defaults as $key => $val) { if (Isset ($config [$key])) { &N Bsp $method = "set_{$key}"; if (method_exists ($this, $method)) { $this-> $method ($config [$ Key]); &NBSP} else { $this-> $key = $config[$key]; } else { $this-> $key = $val; } &NBSP/ //check if file_name was provided. if (!empty ($this->file_name)) { //multiple file upload. if ( Is_array ($this->file_name)) { //clear file name override. $this-& Gt;_file_name_override = ""; //set multiple file name override. $this->_multi_file_name_override = $this->file_name; //single file upload. } else { //set file name override. $this->_f Ile_name_override = $this->file_name; //clear multiple file name override. $this->_multi_file_name_override = ""; &nbSp } { /** * File MIME Type * * detects the (actual) MIME type of the uploaded file, if possible. * The input array is expected to $_files[$field]. * * In the case of multiple uploads, a optional second argument may being * p Assed specifying which array element of the $_files[$field] array * elements should be referenced (name, Typ E, Tmp_name, etc). * * @access protected * @param $file array * @param $count int &NB Sp * @return void / protected function _file_mime_type ($file, $count =0) { &N Bsp;//mutliple file? if (Is_array ($file ["name"]) { $tmp _name = $file ["Tmp_name"] [$count]; & nbsp $type = $file ["type"] [$count]; &NBsp;//single file. &NBSP} else { $tmp _name = $file ["Tmp_name"]; $type = $file ["Type" ]; &NBSP} //we ' ll need this to validate the MIME info string (e.g. Text/plain; char SET=US-ASCII). $REGEXP = "/^ ([a-z-]+/[a-z0-9-.+]+) (; s.+)? $/"; /* Fileinfo extension-most reliable method. * * Unfortunately, prior to PHP 5.3-it's only available as a PECL extens Ion and the * More convenient Fileinfo_mime_type flag doesn ' t exist. */ if (function_exists ("Finfo_file")) { $finfo = Finfo_open (Fileinfo_mime); if (Is_resource ($finfo)) { $mime = @finfo_file ($finfo, $tmp _name); &n Bsp Finfo_close ($finfo); /* accordingTo the comments section of the PHP manual page, * It's possible this function Retu RNs A empty string * for some files (e.g. if they don ' t exist in the magic MIME Databas E. */ if (is_string ($mime) && Preg_match ($reg Exp, $mime, $matches)) { $this->file_type = $matches [1]; & nbsp return; { } /a ugly hack, but Unix-type systems provide a "native" way to detect the file type, * whic H is still more secure than depending on the value of $_files[$field] [' type '], and as it * Ed in issue #750 (https://github.com/EllisLab/CodeIgniter/issues/750)-it ' s better * than Mime_conte Nt_Type () as OK, hence the attempts to try calling the command line with * three different functions. * * Notes: *-the Directory_separator comparison ensures t Hat we ' re not on a Windows system *-Many system admins would disable the exec (), shell_exec (), Pope N () and similar functions * Due to security concerns, hence the function_exists () checks ; * if (directory_separator!== "") { $cmd = "File--bri EF--mime ". Escapeshellarg ($tmp _name)." 2>&1 "; if (function_exists ("exec")) { /* might look confusing, a S $mime is being populated with the "output" when set in the second parameter. * However, we only neeed the "last line", which is the actual return value of exec (), and As SucH-it overwrites * anything that could already is set for $mime previously. This effectively makes the second parameter a dummy * value which us to get the return status code. */ $mime = @exec ($cmd, $mime, $return _status); if ($return _status = 0 && is_string ($mime) && preg_match ($regexp, $mim E, $matches)) { $this->file_type = $matches [1]; RE Turn { } } if ((bool) @ini_get ("safe_mode") = = FALSE && function_exists ("Shell_exec")) { $mime = @ Shell_exec ($cmd); if (strlen ($mime) > 0) { $mime = explode ("n", Trim ($mIME)); if (Preg_match ($regexp, $mime [(Count ($mime)-1)], $matches)) { &NBS p; $this->file_type = $matches [1]; return; }  , if (function_ Exists ("Popen")) { $proc = @popen ($cmd, "R"); if (Is_resource ($proc)) { $mime = @fread ($proc, the same); @pclose ($PROC); if ($mime!== FALSE) { $mime = explode ("n", Trim ($mime); &NB Sp if (Preg_match ($regexp, $mime [(Count ($mime)-1)], $matches)) { $this->file_ Type = $matches [1]; return; &NBSP, { } &NBsp //fall back to the deprecated mime_content_type (), if available (still better than $_files[$field] ["t Ype "] if (function_exists (" Mime_content_type ")) { $this->file_type = @ Mime_content_type ($tmp _name); //it ' s possible that Mime_content_type () returns FALSE or a empty string. if (strlen ($this->file_type) > 0) { return; &NBSP ; &NBSP} } //if all else fails, use $_files default MIME type. $this->file_type = $type; } /** * Set multiple Upload Data * * @a ccess protected * @return void / protected function Set_multi_upload_data () {&N Bsp $this->_multi_upload_data[] = Array ( "file_name"   => $this->file_name, "File_type" => $this->file_type, "file_p Ath " => $this->upload_path, " Full_path " => $this->upload_path. $this-> file_name, "Raw_name" => str_replace ($this->file_ext, "", $this->file_name), "Orig_name" => $this->orig_name, "Client_name" => $this->clie Nt_name "File_ext" => $this->file_ext, "file_size" => $t His->file_size "Is_image" => $this->is_image (), "Image_width" & Nbsp;=> $this->image_width, "Image_height" => $this->image_height, "Image_type" => $this->image_type, "Image_size_str" => $this->image_size_ STR );   /** * Get multiple Upload Data * * @access P Ublic * @return array / public Function get_multi_upload_data () { return $this->_multi_upload_data; } /** * multile File Upload * * @access Public * @param string * @return mixed / Public Function Do_mult I_upload ($field) { //is $_files[$field] set? If not, no reason to continue. if (!isset ($_files[$field)) {return false;} //is This really a multi Uploa D? if (!is_array ($_files[$field] ["name"]) { //fallback to Do_upload method. & nbsp Return $this->do_upload ($field); &NBSP;} //is the upload path valId? &NBSP;IF (! $this->validate_upload_path ()) { //errors'll already is set by Validate_u Pload_path () So just return false return false; &NBSP} //every file would have a separate entry in each of the $_files Associativ e-array elements (name, type, etc). //loop through $_files[$field] ["name"] as representative of total number of FILES. Use count as key in //corresponding elements of the $_files[$field] elements. for ($i =0 $i <count ($_files[$field] ["name"]) $i + +] { //was The file able to is Uploaded? If not, determine the reason why. if (!is_uploaded_file ($_files[$field] ["Tmp_name"] [$i])) { //determine Error number. $error = (!isset ($_files[$field] ["Error"] [$i])? 4: $_files[$field] ["Error"] [$i]; //set Error. switch ($error) { //upload_err_ini_size C ASE 1: $this->set_error ("Upload_file_exceeds_limit"); break; //upload_err_form_size Case 2: $ This->set_error ("Upload_file_exceeds_form_limit"); break; //upload_err_partial Case 3: $th Is->set_error ("upload_file_partial"); break; //upload_err_no_file Case 4: $th Is->set_error ("upload_no_file_selected"); break; //upload_err_no_tmp_dir Case 6: $this->sEt_error ("Upload_no_temp_directory"); break; //upload_err_cant_write Case 7: $this->set_error ("Upload_unable_to_write_file"); break; //upload_err_extension Case 8: $ This->set_error ("Upload_stopped_by_extension"); break; default: ->set_error $this ("upload_no_file_selected"); break; &NBSP} //return failed upload. return FALSE; } //set current file data as class variables. $this->file_temp = $_files[$field] ["Tmp_name"] [$i]; $this->file_size = $_files[$field["Size"] [$i]; $this->_file_mime_type ($_files[$field], $i); $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"] [$i]); $this->file_ext = $this->get_extension ($this->file_name); $this->client_name = $this->file_name; //is The file type allowed to is uploaded? if (! $this->is_allowed_filetype ()) { $this->set_error ("Upload_ Invalid_filetype "); return FALSE; } //if we ' re overriding, let's now make sure the new name and type are all Owed. //check if a filename is supplied for the current file. OtherwIse, use it ' s given name. if (!empty ($this->_multi_file_name_override[$i]) { $this->file_ Name = $this->_prep_filename ($this->_multi_file_name_override[$i]); //if no extension is provided in the File_name Config item and use the uploaded one. if (Strpos ($this->_multi_file_name_override[$i], ".") = = FALSE) { & nbsp $this->file_name. = $this->file_ext; //an extension was provided, lets have it! &NBSP} else { $this->file_ext = $this->get_extension ($this->_mu lti_file_name_override[$i]); &NBSP} if (! $this->is_allowed_filetype (TRUE)) { &N Bsp $this->set_error ("Upload_invalid_filetype"); return FALSE; &NBSP} } //convert The file size to kilobytes. if ($this->file_size > 0) { $this->file_size = round ($this->fil e_size/1024, 2); } //is The file size within the allowed maximum? if (! $this->is_allowed_filesize ()) { $this->set_error ("Upload_ Invalid_filesize "); 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 spaces in the name if ($this->rem Ove_spaces = = TRUE) { $this->file_name = preg_replace ("/s+/", "_", $this->file_name); &nb Sp } * Validate the file name * This function appends a n 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) { &nbsP $this->file_name = $this->set_filename ($this->upload_path, $this->file_name); if ($this->file_name = False) { return FALSE; &nbs P } /* Run the file through the XSS hacking filter &N Bsp * This helps prevent malicious code from being * embedded within a file. scripts can easily * is disguised as images or other file types. */ if ($this->xss_clean) { if ($this ;d O_xss_clean () = FALSE) { $this->set_error ("Upload_unable_to_write_file"); return FALSE; }  , * Move the file to the final Desti Nation &NBSp * to deal with different server configurations * We'll attempt to use copy (). if that fails * We'll use Move_uploaded_file (). one of the two should * reliably work in most environments */ &NBSP;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 Dimensio NS * This sets the image width/height (assuming the * file is an IM Age). we Use this information * in the "Data" FUnction. */ $this->set_image_properties ($this->upload_path. $this- >file_name); //set current file data to Multi_file_upload_data. $this->set_multi_upload_data (); &NBSP} //return all file upload data. return TRUE; &NBSP} }