文件上传类。

支持自定义文件上传、支持扩展多文件上传功能。代码如下

<code>

<?
/**
  * filename:upload.class.php
  * since:2006-11-28
  * description:文件上传类。
  * author feifengxlq<许立强> http://www.phpobject.net/blog
  * version v0.02
  * demo:
  $upload=new upload(array('path'=>'../test','allow_type'=>array('txt')));
  print_r($upload->upfile('userfile'));
  自定义上传文件名
  $upload=new upload();
  print_r($upload->upfile('userfile',array('allow_type'=>array('txt'),'filename'=>'test.txt')));
*/
class upload
{
    
    var $path='/uploadfiles/';//上传文件的路径
    
    var $allow_type=array('jpg','gif');//允许上传的文件类型
    
    var $max_size='2048';//允许的最大文件大小
    
    //var $field='uploadfile';//上传文件的字段名
    
    var $overwrite=false;//是否设置成覆盖模式
    
    var $renamed=true;//是否直接使用上传文件的名称,还是系统自动命名
    
    //private    
    var $upfile=array();//上传后文件信息
    
    var $ext='';//上传文件的扩展名
    
    var $errormsg='';//出错信息
    
    var $filename='';//是否设置了上传后的文件名
    /**
      * 出错模式
      * 0:出错就exit
      * 1:出错返回出错信息
    */
    var $error_mode=0;//出错模式
    
    function upload($options=array())
    {
       //构造
       $this->_set_options($options);
    }
    //上传文件
    function upfile($field,$options=array())
    {
        //设置上传文件的属性
        $this->_set_options($options);
        //获取文件
        $this->_set_upfile($field);
        //检查文件
        $this->_check();
        //设置上传后的文件名
        $this->_set_filename();
        //检查是否出错
        if($this->errormsg)return false;
        //上传文件
        if(@move_uploaded_file($this->upfile['tmp_name'],$this->upfile['filename']))return $this->upfile;
        //上传失败
        $this->error(__FUNCTION__.'():'.$this->upfile['filename'].'上传失败。');
        return false;
    }
    //获取出错信息
    function get_error()
    {
        if($this->errormsg)return $this->errormsg;
        return false;
    }
/**-----------private-----------------------------------------------*/
    /**
      * 设置上传后的文件名
    */
    function _set_filename()
    {
        //是否重命名
        if($this->filename){
            //如果用户设置了文件名
            if(file_exists($this->filename))@unlink($this->filename);
            $this->upfile['filename']=$this->filename;
            return true;
        }
        //检查上传文件路径
        if(!file_exists($this->path))$this->_mkpath($this->path);
        if($this->path[strlen($this->path)-1]!='/')$this->path.='/';//
        
        if($this->renamed){
            $ext=$this->ext;
            if(empty($ext))$ext=$this->_get_ext($this->upfile['name']);
            $filename=uniqid(time()).'.'.$ext;
        }else{
            $filename=$this->upfile['name'];
        }
        //是否覆盖模式
        if(!$this->overwrite){
            //不覆盖,检查是否存在同名文件
            $i=1;
            while(file_exists($this->path.$filename)){
                $filename=$i.'_'.$filename;
                $i++;
            }
        }else{
            //覆盖模式,如果存在改文件,则删除
            if(file_exists($this->path.$filename))@unlink($this->path.$filename);
        }
        $this->upfile['filename']=$this->path.$filename;
    }
    /**
      * 检查文件是否符合需要
    */
    function _check()
    {
        //检查文件大小
        $this->_check_size();
        //检查文件类型
        $this->_check_type();        
    }    
    /**
      * 设置属性
    */
    function _set_options($options){
       if(is_array($options)){
           foreach($options as $key=>$value){
               if(in_array($key,array('path','allow_type','max_size','overwrite','renamed','error_mode','filename'))){
                   $this->_set($key,$value);
               }
           }
        }
    }
    /**
      * 检查文件类型getimagesize
    */
    function _check_type()
    {
        $this->_get_ext($this->upfile['name']);
        $this->upfile['filetype']=$this->ext;
        if(in_array($this->ext,$this->allow_type))
        {
            //检查mine类型
            $file_mine=$this->upfile['type'];
            if(empty($file_mine))return true;
            //检查mine类型是否符合
            $this->_check_mine($file_mine);
        }else{
            $this->error(__FUNCTION__.'():'.$this->upfile['name'].'文件类型'.$this->ext.'不符合。只允许上传'.implode(',',$this->allow_type));
        }
    }
    /**
      * 检查上传文件的mine类型
    */
    function _check_mine($mine)
    {
        require_once('filetype.php');
        $pass=false;
        foreach($this->allow_type as $type){
            if(is_array($filetype[$type])){
                if(in_array($mine,$filetype[$type])){
                    //
                    $pass=true;
                    break;
                }
            }elseif($filetype[$type]==$mine){
               $pass=true;
               break;
            }
        }
        if(!$pass)$this->error(__FUNCTION__.'():'.$this->upfile['name'].'文件mine类型不符合。只允许上传'.implode(',',$this->allow_type));
    }
    /**
      * 获取文件的后缀
    */
    function _get_ext($file){
        $ext = explode(".", $file);
        $ext = $ext[count($ext) - 1];
        $this->ext=strtolower($ext);
        return $this->ext;
    }
    /**
      * 检查文件大小
    */
    function _check_size()
    {
        if($this->upfile['size']>$this->max_size*1024)
        $this->error(__FUNCTION__.'():'.$this->upfile['name'].'文件大小超过了限制'.$this->max_size.'MB');
    }
    /**
      * 获取文件
      * @param field
      * @return  
    */
    function _set_upfile($field)
    {
        if(!$_FILES[$field])$this->error(__FUNCTION__.'():文件不存在!');
        if($_FILES[$field]['error']>=1)$this->error(__FUNCTION__.'():'.$this->_get_upload_error($_FILES[$field]['error']));
        $this->upfile=$_FILES[$field];
    }
    
    
    function _set($key,$value){
        $this->$key=$value;
    }
    
    /**
      * 构造目录
    */
    function _mkpath($path,$mode=700){
        $path=str_replace("//","/",$path);
        $path_info=explode('/',$path);
        $total=count($path_info);
        $path='';
        for($i=0;$i<$total;$i++)
        {
            $path.=$path_info[$i].'/';
            if(empty($path_info[$i]))continue;
            if(file_exists($path))
            {
                continue;
            }else{
                if(!@mkdir($path,$mode))$this->error(__FUNCTION__.'(),创建'.$path.'出错!');
            }
        }
        return true;
    }
    /**
      * 格式化文件大小
    */
    function format_size($size)
    {
        if($size<1024){
            return $size.'B';
        }elseif ($size<1024*1024){
            return number_format((double)($size/1024),2).'KB';
        }else{
            return number_format((double)($size/(1024*1024)),2).'MB';
        }
    }
    /**
      * 获取上传出错信息(根据$_FILES['file']['error]])
    */
    function _get_upload_error($id)
    {
        switch($id)
        {
            case 1:
                return '上传的文件超过了 php.ini 中 upload_max_filesize 选项限制的值';
            case 2:
                return '上传文件的大小超过了 HTML 表单中 MAX_FILE_SIZE 选项指定的值';
            case 3:
                return '文件只有部分被上传';
            case 4:
                return '没有文件被上传';
            case 5:
                return '未知错误!';
            case 6:
                return '找不到临时文件夹';
            case 7:
                return '文件写入失败';
            default:
                return '未知错误!';
        }
    }
    /**
      * 出错处理!
    */
    function error($msg)
    {
        if($this->error_mode==0)die('ERROR : file '.__FILE__.' function '.$msg);
        $this->errormsg.='ERROR : file '.__FILE__.' function '.$msg."/n";
    }
}
?>[/code2]


其中几个简单的调用demo


[code2]<?
$upload=new upload(array('path'=>'../test','allow_type'=>array('txt')));
  print_r($upload->upfile('userfile'));
  自定义上传文件名
  $upload=new upload();
  print_r($upload->upfile('userfile',array('allow_type'=>array('txt'),'filename'=>'test.txt')));
?> [/code2]

另外其中有个filetype.php文件
常用文件得mine类型。


<?
$filetype=array();
$filetype['hqx']="application/mac-binhex40";
$filetype['bin']="application/octet-stream";
$filetype['oda']="application/oda";
$filetype['pdf']="application/pdf";
$filetype['ai']="application/postsrcipt";
$filetype['eps']="application/postsrcipt";
$filetype['es']="application/postsrcipt";
$filetype['rtf']="application/rtf";
$filetype['mif']="application/x-mif";
$filetype['csh']="application/x-csh";
$filetype['dvi']="application/x-dvi";
$filetype['hdf']="application/x-hdf";
$filetype['nc']="application/x-netcdf";
$filetype['cdf']="application/x-netcdf";
$filetype['latex']="application/x-latex";
$filetype['ts']="application/x-troll-ts";
$filetype['src']="application/x-wais-source";
$filetype['zip']="application/zip";
$filetype['bcpio']="application/x-bcpio";
$filetype['cpio']="application/x-cpio";
$filetype['gtar']="application/x-gtar";
$filetype['shar']="application/x-shar";
$filetype['sv4cpio']="application/x-sv4cpio";
$filetype['sv4crc']="application/x-sv4crc";
$filetype['tar']="application/x-tar";
$filetype['ustar']="application/x-ustar";
$filetype['man']="application/x-troff-man";
$filetype['sh']="application/x-sh";
$filetype['tcl']="application/x-tcl";
$filetype['tex']="application/x-tex";
$filetype['texi']="application/x-texinfo";
$filetype['texinfo']="application/x-texinfo";
$filetype['t']="application/x-troff";
$filetype['tr']="application/x-troff";
$filetype['roff']="application/x-troff";
$filetype['shar']="application/x-shar";
$filetype['me']="application/x-troll-me";
$filetype['ts']="application/x-troll-ts";
$filetype['gif']="image/gif";
$filetype['jpeg']="image/pjpeg";
$filetype['jpg']=array("image/pjpeg","image/jpeg");
$filetype['jpe']="image/pjpeg";
$filetype['ras']="image/x-cmu-raster";
$filetype['pbm']="image/x-portable-bitmap";
$filetype['ppm']="image/x-portable-pixmap";
$filetype['xbm']="image/x-xbitmap";
$filetype['xwd']="image/x-xwindowdump";
$filetype['ief']="image/ief";
$filetype['tif']="image/tiff";
$filetype['tiff']="image/tiff";
$filetype['pnm']="image/x-portable-anymap";
$filetype['pgm']="image/x-portable-graymap";
$filetype['rgb']="image/x-rgb";
$filetype['xpm']="image/x-xpixmap";
$filetype['txt']="text/plain";
$filetype['c']="text/plain";
$filetype['cc']="text/plain";
$filetype['h']="text/plain";
$filetype['html']="text/html";
$filetype['htm']="text/html";
$filetype['htl']="text/html";
$filetype['rtx']="text/richtext";
$filetype['etx']="text/x-setext";
$filetype['tsv']="text/tab-separated-values";
$filetype['mpeg']="video/mpeg";
$filetype['avi']="video/avi";
$filetype['rm']="video/rm";
$filetype['rmvb']="video/rmvb";
$filetype['wmv']="video/x-ms-wmv";
$filetype['flv']="application/octet-stream";
$filetype['mpg']="video/mpeg";
$filetype['mpe']="video/mpeg";
$filetype['avi']="video/x-msvideo";
$filetype['qt']="video/quicktime";
$filetype['mov']="video/quicktime";
$filetype['moov']="video/quicktime";
$filetype['movie']="video/x-sgi-movie";
$filetype['au']="audio/basic";
$filetype['mp3']="audio/mp3";
$filetype['snd']="audio/basic";
$filetype['wav']="audio/wav";
$filetype['wma']="audio/x-ms-wma";
$filetype['aif']="audio/x-aiff";
$filetype['aiff']="audio/x-aiff";
$filetype['aifc']="audio/x-aiff";
$filetype['swf']="application/x-shockwave-flash";
$filetype['doc']="application/msword";
$filetype['ini']='application/octet-stream';
?>


</code>

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章