<?php
/*------------*/
class UploadFile
{
var $user_post_file = array();
var $save_file_path = '';
var $max_file_size = '';
var $allow_type = array('gif','jpg','png','zip','rar','txt','doc','pdf');
var $final_file_path = '';
var $save_info = array();
var $error_info = array();
/**
*构造函数,用于初始化信息。
*
*@param Array $file
*@param String $path
*@param Integer $size
*@param Array $type
*/
function __construct($file,$path,$size = 2097152,$type='')
{
$this->user_post_file = $file;
$this->save_file_path = $path;
$this->max_file_size = $size;
if(!$type=''){
$this->allow_type[] = $type;
}
}
/**
*
*
*@access public
*@return int
*/
function upload()
{
for($i=0;$i<count($this->user_post_file['name']);$i++)
{
if($this->user_post_file['error'][$i] == 0){//上传文件状态正常
//获取当前文件名,临时文件名,大小,类型,扩展名
$name = $this->user_post_file['name'][$i];
$tmp_name = $this->user_post_file['tmp_name'][$i];
$size = $this->user_post_file['size'][$i];
$type = $this->user_post_file['type'][$i];
$ext_name = $this->getExtName($name);
//文件大小
if(!$this->checkSize($size)){
$this->error_info[] = '您上传的文件:'.$name.'太大';
continue;
}
//扩展名
if(!$this->checkType($ext_name)){
$this->error_info[] = '您上传的文件:'.$name.'不合法';
continue;
}
//非法上传
if(!is_uploaded_file($tmp_name)){
$this->error_info[] = '您上传的文件:'.$name.'属于非法提交';
continue;
}
//
$basename = $this->getBaseName($name,".".$ext_name);
$final_filename = $basename.'-'.time().'-'.rand(1,10000).'.'.$ext_name;
$this->final_file_path = $this->save_file_path.'/'.$final_filename;
if(!move_uploaded_file($tmp_name,$this->final_file_path)){
$this->error_info = $this->user_post_file['error'][$i];
continue;
}
//
$this->save_info[] = array(
"name" => $name,
"ext_name" => $ext_name,
"type" => $type,
"size" => $size,
"final_filename" => $final_filename,
"path" => $this->final_file_path
);
}
}
return count($this->save_info);
}
/*
*检查用户上传文件的大小时候合法
*
*@param Integer $size
*@access private
*@return boolean
*/
function checkSize($size)
{
if($size > $this->max_file_size){
return FALSE;
}
return TRUE;
}
/*
*检查用户上传文件的类型是否合法
*
*@access private
*@return boolean
*/
function checkType($extension)
{
foreach($this->allow_type as $type){
if(strcasecmp($extension,$type) == 0){
return TRUE;
}
}
return FALSE;
}
/*
*获取文件的扩展名
*
*@param string $filename
*@access private
*@return string
*/
function getExtName($filename)
{
$p = pathinfo($filename);
return $p['extension'];
}
/*
*获取文件名(不包括扩展名)
*
*@param string $filename
*@param string $type
*@access private
*@return boolean
*/
function getBaseName($filename,$ext_name)
{
$basename = basename($filename,$ext_name);
return $basename;
}
/*
*
*
*
*/
function showErrorInfo()
{
if(count($this->error_info) != 0){
//echo 'error...<br/>';
foreach($this->error_info as $k=>$v){
echo ($k+1),':',$v,'<br/>';
}
}
}
function getSaveInfo()
{
return $this->save_info;
}
}
//$upload = new UploadFile('','');
//$upload = new UploadFile();
//$upload->showErrorInfo();
?>
|