热门标签 | HotTags
当前位置:  开发笔记 > 编程语言 > 正文

codeigniter教程之多文件上传使用示例

这篇文章主要介绍了codeigniter多文件上传使用示例,需要的朋友可以参考下
CI框架

代码如下:

/**
* Multi-Upload
*
* Extends CodeIgniters native Upload class to add support for multiple
* uploads.
*
* @package CodeIgniter
* @subpackage Libraries
* @category Uploads
*/
class 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= array()){
//Upload default settings.
$defaults = array(
"max_size" => 0,
"max_width" => 0,
"max_height" => 0,
"max_filename" => 0,
"allowed_types" => "",
"file_temp" => "",
"file_name" => "",
"orig_name" => "",
"file_type" => "",
"file_size" => "",
"file_ext" => "",
"upload_path" => "",
"overwrite" => FALSE,
"encrypt_name" => FALSE,
"is_image" => FALSE,
"image_width" => "",
"image_height" => "",
"image_type" => "",
"image_size_str" => "",
"error_msg" => array(),
"mimes" => array(),
"remove_spaces" => TRUE,
"xss_clean" => FALSE,
"temp_prefix" => "temp_file_",
"client_name" => ""
);

//Set each configuration.
foreach($defaults as $key => $val){
if(isset($config[$key])){
$method = "set_{$key}";
if(method_exists($this, $method)){
$this->$method($config[$key]);
} else {
$this->$key = $config[$key];
}
} else {
$this->$key = $val;
}
}

//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->_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->_file_name_override = $this->file_name;

//Clear multiple file name override.
$this->_multi_file_name_override = "";
}
}
}


/**
* File MIME Type
*
* Detects the (actual) MIME type of the uploaded file, if possible.
* The input array is expected to be $_FILES[$field].
*
* In the case of multiple uploads, a optional second argument may be
* passed specifying which array element of the $_FILES[$field] array
* elements should be referenced (name, type, tmp_name, etc).
*
* @access protected
* @param $file array
* @param $count int
* @return void
*/
protected function _file_mime_type($file, $count=0){
//Mutliple file?
if(is_array($file["name"])){
$tmp_name = $file["tmp_name"][$count];
$type = $file["type"][$count];
//Single file.
} else {
$tmp_name = $file["tmp_name"];
$type = $file["type"];
}

//We'll need this to validate the MIME info string (e.g. text/plain; charset=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 extension 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);
finfo_close($finfo);

/* According to the comments section of the PHP manual page,
* it is possible that this function returns an empty string
* for some files (e.g. if they don't exist in the magic MIME database).
*/
if(is_string($mime) && preg_match($regexp, $mime, $matches)){
$this->file_type = $matches[1];
return;
}
}
}

/* This is an ugly hack, but UNIX-type systems provide a "native" way to detect the file type,
* which is still more secure than depending on the value of $_FILES[$field]['type'], and as it
* was reported in issue #750 (https://github.com/EllisLab/CodeIgniter/issues/750) - it's better
* than mime_content_type() as well, hence the attempts to try calling the command line with
* three different functions.
*
* Notes:
* - the DIRECTORY_SEPARATOR comparison ensures that we're not on a Windows system
* - many system admins would disable the exec(), shell_exec(), popen() and similar functions
* due to security concerns, hence the function_exists() checks
*/
if(DIRECTORY_SEPARATOR !== "\\"){
$cmd = "file --brief --mime ".escapeshellarg($tmp_name)." 2>&1";

if(function_exists("exec")){
/* This might look confusing, as $mime is being populated with all of 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 be set for $mime previously. This effectively makes the second parameter a dummy
* value, which is only put to allow us to get the return status code.
*/
$mime = @exec($cmd, $mime, $return_status);
if($return_status === 0 && is_string($mime) && preg_match($regexp, $mime, $matches)){
$this->file_type = $matches[1];
return;
}
}
}

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)){
$this->file_type = $matches[1];
return;
}
}
}

if(function_exists("popen")){
$proc = @popen($cmd, "r");
if(is_resource($proc)){
$mime = @fread($proc, 512);
@pclose($proc);
if($mime !== FALSE){
$mime = explode("\n", trim($mime));
if(preg_match($regexp, $mime[(count($mime) - 1)], $matches)){
$this->file_type = $matches[1];
return;
}
}
}
}

//Fall back to the deprecated mime_content_type(), if available (still better than $_FILES[$field]["type"])
if(function_exists("mime_content_type")){
$this->file_type = @mime_content_type($tmp_name);
//It's possible that mime_content_type() returns FALSE or an empty string.
if(strlen($this->file_type) > 0){
return;
}
}

//If all else fails, use $_FILES default mime type.
$this->file_type = $type;
}


/**
* Set Multiple Upload Data
*
* @access protected
* @return void
*/
protected function set_multi_upload_data(){
$this->_multi_upload_data[] = array(
"file_name" => $this->file_name,
"file_type" => $this->file_type,
"file_path" => $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->client_name,
"file_ext" => $this->file_ext,
"file_size" => $this->file_size,
"is_image" => $this->is_image(),
"image_width" => $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 public
* @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_multi_upload($field){
//Is $_FILES[$field] set? If not, no reason to continue.
if(!isset($_FILES[$field])){ return false; }

//Is this really a multi upload?
if(!is_array($_FILES[$field]["name"])){
//Fallback to do_upload method.
return $this->do_upload($field);
}

//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;
}

//Every file will have a separate entry in each of the $_FILES associative 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 //Was the file able to be 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
case 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:
$this->set_error("upload_file_partial");
break;
//UPLOAD_ERR_NO_FILE
case 4:
$this->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:
$this->set_error("upload_no_file_selected");
break;
}

//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 be 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 is allowed.
//Check if a filename was 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 was provided in the file_name config item, use the uploaded one.
if(strpos($this->_multi_file_name_override[$i], ".") === FALSE){
$this->file_name .= $this->file_ext;
//An extension was provided, lets have it!
} else {
$this->file_ext = $this->get_extension($this->_multi_file_name_override[$i]);
}

if(!$this->is_allowed_filetype(TRUE)){
$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("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 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);

//Set current file data to multi_file_upload_data.
$this->set_multi_upload_data();
}

//Return all file upload data.
return TRUE;
}
}

推荐阅读
  • 2月4日每日安全热点节日期间某企远程办公遭XRed攻击 ... [详细]
  • Java验证码——kaptcha的使用配置及样式
    本文介绍了如何使用kaptcha库来实现Java验证码的配置和样式设置,包括pom.xml的依赖配置和web.xml中servlet的配置。 ... [详细]
  • 在Docker中,将主机目录挂载到容器中作为volume使用时,常常会遇到文件权限问题。这是因为容器内外的UID不同所导致的。本文介绍了解决这个问题的方法,包括使用gosu和suexec工具以及在Dockerfile中配置volume的权限。通过这些方法,可以避免在使用Docker时出现无写权限的情况。 ... [详细]
  • 云原生边缘计算之KubeEdge简介及功能特点
    本文介绍了云原生边缘计算中的KubeEdge系统,该系统是一个开源系统,用于将容器化应用程序编排功能扩展到Edge的主机。它基于Kubernetes构建,并为网络应用程序提供基础架构支持。同时,KubeEdge具有离线模式、基于Kubernetes的节点、群集、应用程序和设备管理、资源优化等特点。此外,KubeEdge还支持跨平台工作,在私有、公共和混合云中都可以运行。同时,KubeEdge还提供数据管理和数据分析管道引擎的支持。最后,本文还介绍了KubeEdge系统生成证书的方法。 ... [详细]
  • Windows下配置PHP5.6的方法及注意事项
    本文介绍了在Windows系统下配置PHP5.6的步骤及注意事项,包括下载PHP5.6、解压并配置IIS、添加模块映射、测试等。同时提供了一些常见问题的解决方法,如下载缺失的msvcr110.dll文件等。通过本文的指导,读者可以轻松地在Windows系统下配置PHP5.6,并解决一些常见的配置问题。 ... [详细]
  • 知识图谱——机器大脑中的知识库
    本文介绍了知识图谱在机器大脑中的应用,以及搜索引擎在知识图谱方面的发展。以谷歌知识图谱为例,说明了知识图谱的智能化特点。通过搜索引擎用户可以获取更加智能化的答案,如搜索关键词"Marie Curie",会得到居里夫人的详细信息以及与之相关的历史人物。知识图谱的出现引起了搜索引擎行业的变革,不仅美国的微软必应,中国的百度、搜狗等搜索引擎公司也纷纷推出了自己的知识图谱。 ... [详细]
  • MACElasticsearch安装步骤及验证方法
    本文介绍了MACElasticsearch的安装步骤,包括下载ZIP文件、解压到安装目录、启动服务,并提供了验证启动是否成功的方法。同时,还介绍了安装elasticsearch-head插件的方法,以便于进行查询操作。 ... [详细]
  • 推荐系统遇上深度学习(十七)详解推荐系统中的常用评测指标
    原创:石晓文小小挖掘机2018-06-18笔者是一个痴迷于挖掘数据中的价值的学习人,希望在平日的工作学习中,挖掘数据的价值, ... [详细]
  • Google Play推出全新的应用内评价API,帮助开发者获取更多优质用户反馈。用户每天在Google Play上发表数百万条评论,这有助于开发者了解用户喜好和改进需求。开发者可以选择在适当的时间请求用户撰写评论,以获得全面而有用的反馈。全新应用内评价功能让用户无需返回应用详情页面即可发表评论,提升用户体验。 ... [详细]
  • FeatureRequestIsyourfeaturerequestrelatedtoaproblem?Please ... [详细]
  • JVM(三)虚拟机栈 多合一总述
    虚拟机栈概述虚拟机栈出现背景:由于跨平台性的设计,Java的指令都是根据栈来设计的。不同CPU架构不同,所以不能设计为基于寄存器的跨平台的优点:指令集小,编译器容易实现,缺点是性能 ... [详细]
  • Skywalking系列博客1安装单机版 Skywalking的快速安装方法
    本文介绍了如何快速安装单机版的Skywalking,包括下载、环境需求和端口检查等步骤。同时提供了百度盘下载地址和查询端口是否被占用的命令。 ... [详细]
  • sklearn数据集库中的常用数据集类型介绍
    本文介绍了sklearn数据集库中常用的数据集类型,包括玩具数据集和样本生成器。其中详细介绍了波士顿房价数据集,包含了波士顿506处房屋的13种不同特征以及房屋价格,适用于回归任务。 ... [详细]
  • JDK1.7及之前的JMM先看一张图,很清晰的说明了JAVA内存结构布局:JAVA内存结构主要分为三大块:堆内存、方法区和栈。堆内存是JVM中最大的一块内存,由年轻代和老年代组成。 ... [详细]
  • 小程序引入外部文件的方式是:import**.wxss;因为业务需要,正在开发的小程序中需要使用iconfont,很容易想到了H5的引 ... [详细]
author-avatar
夜的泪2502877077
这个家伙很懒,什么也没留下!
PHP1.CN | 中国最专业的PHP中文社区 | DevBox开发工具箱 | json解析格式化 |PHP资讯 | PHP教程 | 数据库技术 | 服务器技术 | 前端开发技术 | PHP框架 | 开发工具 | 在线工具
Copyright © 1998 - 2020 PHP1.CN. All Rights Reserved | 京公网安备 11010802041100号 | 京ICP备19059560号-4 | PHP1.CN 第一PHP社区 版权所有