再附一段取自摇光框架的PHP上传类:
[PHP] 纯文本查看 复制代码 /**
* 数据上传类: 快速接收用户传来的文件.
*/
class UploadData
{
const SUCCESS_UPLOAD = "文件上传成功.";
const ERROR_NO_EXTENSION = "错误: 不允许使用的扩展名.";
const ERROR_FILE_TOOBIG = "错误: 文件大小超出限制.";
const ERROR_FILE_SAMENAME = "错误: 文件与已有文件重名.";
const EXTENSION_NO_PHP = array("php");
public $log_obj;
/**
* 构造方法: 检测是否存在文件存贮目录.
*/
public function __construct(){
//实例化日志操作类
$this->log_obj = new LogHandler;
if(!file_exists("./data/")){
mkdir("./data/");
}
}
/**
* 成员方法: 监听用户是否上传.
* [String] $file_dir: 文件存储目录.
* [String] $file_name: 文件名字 (可选).
* [Array] $extension: 允许或不允许的文件扩展名集合 (可选).
* [bool] $extension_whitelist: 扩展名检测为白名单模式还是黑名单模式,$extension设置后才有效 (可选).
* [Int] $file_max_size: 允许的文件最大的大小,以MB为单位 (可选).
* [String] $file_KeyName: 前端表单里input标签的name属性的值 (可选).
*/
public function monitor_upload($file_dir , $file_name = null , $extension = null , $extension_whitelist = true , $file_max_size = 2048 , $file_KeyName = "file"){
//将$file_max_size的单位从MB转换为B
$file_max_size = $file_max_size * 1024 * 1024;
//检测是否传入了文件
if(isset($_FILES[$file_KeyName])){
//是否使用用户传入的文件的原名
if(is_null($file_name)){$file_name = $_FILES[$file_KeyName]["name"];}
if($_FILES[$file_KeyName]["size"] > $file_max_size){
$this->log_obj->log_write(null , array("Class: ".__CLASS__." Function: ".__FUNCTION__." return: ".$this::ERROR_FILE_TOOBIG));
TpPrint::common_print($this::ERROR_FILE_TOOBIG);
return $this::ERROR_FILE_TOOBIG;
}
//检测指定的二级存贮目录是否存在.
if(!file_exists("./data/".$file_dir)){
mkdir("./data/".$file_dir);
}
//检测是以白名单模式还是黑名单模式筛选文件扩展名
if(!is_null($extension)){
if($extension_whitelist){
//白名单模式
$file_extension = get_file_extension($_FILES[$file_KeyName]["name"]);
if(!in_array($file_extension , $extension)){
$this->log_obj->log_write(null , array("Class: ".__CLASS__." Function: ".__FUNCTION__." return: ".$this::ERROR_NO_EXTENSION));
TpPrint::common_print($this::ERROR_NO_EXTENSION);
return $this::ERROR_NO_EXTENSION;
}
}else{
//黑名单模式
$file_extension = get_file_extension($_FILES[$file_KeyName]["name"]);
if(in_array($file_extension , $extension)){
$this->log_obj->log_write(null , array("Class: ".__CLASS__." Function: ".__FUNCTION__." return: ".$this::ERROR_NO_EXTENSION));
TpPrint::common_print($this::ERROR_NO_EXTENSION);
return $this::ERROR_NO_EXTENSION;
}
}
}
if(file_exists("./data/".$file_dir."/".$file_name)){
$this->log_obj->log_write(null , array("Class: ".__CLASS__." Function: ".__FUNCTION__." return: ".$this::ERROR_FILE_SAMENAME));
TpPrint::common_print($this::ERROR_FILE_SAMENAME);
return $this::ERROR_FILE_SAMENAME;
}
//从缓存目录将文件移动至指定目录
move_uploaded_file($_FILES[$file_KeyName]["tmp_name"] , "./data/".$file_dir."/".$file_name);
if(file_exists("./data/".$file_dir."/".$file_name)){
$this->log_obj->log_write(null , array("Class: ".__CLASS__." Function: ".__FUNCTION__." return: ".$this::SUCCESS_UPLOAD));
TpPrint::common_print($this::SUCCESS_UPLOAD , "提示信息" , true);
return true;
}
}
}
}
|