2008-05-14

PHP文件上传处理类

昨晚研究PHP的文件上传方面的东西,搞到凌晨3点多,终于研究出这个文件上传处理类。昨晚写了一半,下午再把剩下的写完。测试了一下,暂时没发现什么问题。包括批量上传文件,给图片添加水印,生成图像缩略图等功能,附件目录可使用日期参数自定义格式。先把代码贴出来分享一下吧:

PHP代码
  1. <?php   
  2. //-------------------------------------   
  3. // 文件说明:文件上传处理类   
  4. // 文件作者:Jesse Lee   
  5. // 作者主页:http://www.lisijie.com.cn   
  6. // 最后更新:2008-5-14   
  7. //-------------------------------------   
  8. if (!defined('IN_JBLOG')) {   
  9.     exit('Access Denied');   
  10. }   
  11.   
  12. class upload {   
  13.   
  14.     var $dir;            //附件存放物理目录   
  15.     var $time;           //自定义文件上传时间   
  16.     var $allow_types;    //允许上传附件类型   
  17.     var $field;          //上传控件名称   
  18.     var $maxsize;        //最大允许文件大小,单位为KB   
  19.   
  20.     var $thumb_width;    //缩略图宽度   
  21.     var $thumb_height;   //缩略图高度   
  22.   
  23.     var $watermark_file//水印图片地址   
  24.     var $watermark_pos;  //水印位置   
  25.     var $watermark_trans;//水印透明度   
  26.   
  27.   
  28.     //构造函数   
  29.     //$types : 允许上传的文件类型 , $maxsize : 允许大小 ,  $field : 上传控件名称 , $time : 自定义上传时间   
  30.     function upload($types = 'jpg|png'$maxsize = 1024, $field = 'attach'$time = '') {   
  31.         $this->allow_types = explode('|',$types);   
  32.         $this->maxsize = $maxsize * 1024;   
  33.         $this->field = $field;   
  34.         $this->time = $time ? $time : time();   
  35.     }   
  36.   
  37.     //设置并创建文件具体存放的目录   
  38.     //$basedir  : 基目录,必须为物理路径   
  39.     //$filedir  : 自定义子目录,可用参数{y}、{m}、{d}   
  40.     function set_dir($basedir,$filedir = '') {   
  41.         $dir = $basedir;   
  42.         !is_dir($dir) && @mkdir($dir,0777);   
  43.         if (!empty($filedir)) {   
  44.             $filedir = str_replace(array('{y}','{m}','{d}'),array(date('Y',$this->time),date('m',$this->time),date('d',$this->time)),strtolower($filedir));   
  45.             $dirs = explode('/',$filedir);   
  46.             foreach ($dirs as $d) {   
  47.                 !empty($d) && $dir .= $d.'/';   
  48.                 !is_dir($dir) && @mkdir($dir,0777);   
  49.             }   
  50.         }   
  51.         $this->dir = $dir;   
  52.     }   
  53.   
  54.     //图片缩略图设置,如果不生成缩略图则不用设置   
  55.     //$width : 缩略图宽度 , $height : 缩略图高度   
  56.     function set_thumb ($width = 0, $height = 0) {   
  57.         $this->thumb_width  = $width;   
  58.         $this->thumb_height = $height;   
  59.     }   
  60.   
  61.     //图片水印设置,如果不生成添加水印则不用设置   
  62.     //$file : 水印图片 , $pos : 水印位置 , $trans : 水印透明度   
  63.     function set_watermark ($file$pos = 6, $trans = 80) {   
  64.         $this->watermark_file  = $file;   
  65.         $this->watermark_pos   = $pos;   
  66.         $this->watermark_trans = $trans;   
  67.     }   
  68.   
  69.     /*----------------------------------------------------------------  
  70.     执行文件上传,处理完返回一个包含上传成功或失败的文件信息数组,  
  71.     其中:name 为文件名,上传成功时是上传到服务器上的文件名,上传失败则是本地的文件名  
  72.           dir  为服务器上存放该附件的物理路径,上传失败不存在该值  
  73.           size 为附件大小,上传失败不存在该值  
  74.           flag 为状态标识,1表示成功,-1表示文件类型不允许,-2表示文件大小超出  
  75.     -----------------------------------------------------------------*/  
  76.     function execute() {   
  77.         $files = array(); //成功上传的文件信息   
  78.         $field = $this->field;   
  79.         $keys = array_keys($_FILES[$field]['name']);   
  80.         foreach ($keys as $key) {   
  81.             if (!$_FILES[$field]['name'][$key]) continue;   
  82.                
  83.             $fileext = $this->fileext($_FILES[$field]['name'][$key]); //获取文件扩展名   
  84.             $filename = date('Ymdhis',$this->time).mt_rand(10,99).'.'.$fileext//生成文件名   
  85.             $filedir = $this->dir;  //附件实际存放目录   
  86.             $filesize = $_FILES[$field]['size'][$key]; //文件大小   
  87.                
  88.             //文件类型不允许   
  89.             if (!in_array($fileext,$this->allow_types)) {   
  90.                 $files[$key]['name'] = $_FILES[$field]['name'][$key];   
  91.                 $files[$key]['flag'] = -1;   
  92.                 continue;   
  93.             }   
  94.   
  95.             //文件大小超出   
  96.             if ($filesize > $this->maxsize) {   
  97.                 $files[$key]['name'] = $_FILES[$field]['name'][$key];   
  98.                 $files[$key]['name'] = $filesize;   
  99.                 $files[$key]['flag'] = -2;   
  100.                 continue;   
  101.             }   
  102.   
  103.             $files[$key]['name'] = $filename;   
  104.             $files[$key]['dir'] = $filedir;   
  105.             $files[$key]['size'] = $filesize;   
  106.   
  107.             //保存上传文件并删除临时文件   
  108.             if (is_uploaded_file($_FILES[$field]['tmp_name'][$key])) {   
  109.                 move_uploaded_file($_FILES[$field]['tmp_name'][$key],$filedir.$filename);   
  110.                 @unlink($_FILES[$field]['tmp_name'][$key]);   
  111.                 $files[$key]['flag'] = 1;   
  112.   
  113.                 //对图片进行加水印和生成缩略图   
  114.                 if (in_array($fileext,array('jpg','png'))) {   
  115.                     if ($this->thumb_width) {   
  116.                         if ($this->create_thumb($filedir.$filename,$filedir.'thumb_'.$filename)) {   
  117.                             $files[$key]['thumb'] = 'thumb_'.$filename;  //缩略图文件名   
  118.                         }   
  119.                     }   
  120.                     $this->create_watermark($filedir.$filename);   
  121.                 }   
  122.             }   
  123.         }   
  124.   
  125.         return $files;   
  126.     }   
  127.   
  128.     //创建缩略图,以相同的扩展名生成缩略图   
  129.     //$src_file : 来源图像路径 , $thumb_file : 缩略图路径   
  130.     function create_thumb ($src_file,$thumb_file) {   
  131.         $t_width  = $this->thumb_width;   
  132.         $t_height = $this->thumb_height;   
  133.   
  134.         if (!file_exists($src_file)) return false;   
  135.   
  136.         $src_info = getImageSize($src_file);   
  137.   
  138.         //如果来源图像小于或等于缩略图则拷贝源图像作为缩略图   
  139.         if ($src_info[0] <= $t_width && $src_info[1] <= $t_height) {   
  140.             if (!copy($src_file,$thumb_file)) {   
  141.                 return false;   
  142.             }   
  143.             return true;   
  144.         }   
  145.   
  146.         //按比例计算缩略图大小   
  147.         if ($src_info[0] - $t_width > $src_info[1] - $t_height) {   
  148.             $t_height = ($t_width / $src_info[0]) * $src_info[1];   
  149.         } else {   
  150.             $t_width = ($t_height / $src_info[1]) * $src_info[0];   
  151.         }   
  152.   
  153.         //取得文件扩展名   
  154.         $fileext = $this->fileext($src_file);   
  155.   
  156.         switch ($fileext) {   
  157.             case 'jpg' :   
  158.                 $src_img = ImageCreateFromJPEG($src_file); break;   
  159.             case 'png' :   
  160.                 $src_img = ImageCreateFromPNG($src_file); break;   
  161.             case 'gif' :   
  162.                 $src_img = ImageCreateFromGIF($src_file); break;   
  163.         }   
  164.   
  165.         //创建一个真彩色的缩略图像   
  166.         $thumb_img = @ImageCreateTrueColor($t_width,$t_height);   
  167.   
  168.         //ImageCopyResampled函数拷贝的图像平滑度较好,优先考虑   
  169.         if (function_exists('imagecopyresampled')) {   
  170.             @ImageCopyResampled($thumb_img,$src_img,0,0,0,0,$t_width,$t_height,$src_info[0],$src_info[1]);   
  171.         } else {   
  172.             @ImageCopyResized($thumb_img,$src_img,0,0,0,0,$t_width,$t_height,$src_info[0],$src_info[1]);   
  173.         }   
  174.   
  175.         //生成缩略图   
  176.         switch ($fileext) {   
  177.             case 'jpg' :   
  178.                 ImageJPEG($thumb_img,$thumb_file); break;   
  179.             case 'gif' :   
  180.                 ImageGIF($thumb_img,$thumb_file); break;   
  181.             case 'png' :   
  182.                 ImagePNG($thumb_img,$thumb_file); break;   
  183.         }   
  184.   
  185.         //销毁临时图像   
  186.         @ImageDestroy($src_img);   
  187.         @ImageDestroy($thumb_img);   
  188.   
  189.         return true;   
  190.   
  191.     }   
  192.   
  193.     //为图片添加水印   
  194.     //$file : 要添加水印的文件   
  195.     function create_watermark ($file) {   
  196.   
  197.         //文件不存在则返回   
  198.         if (!file_exists($this->watermark_file) || !file_exists($file)) return;   
  199.         if (!function_exists('getImageSize')) return;   
  200.            
  201.         //检查GD支持的文件类型   
  202.         $gd_allow_types = array();   
  203.         if (function_exists('ImageCreateFromGIF')) $gd_allow_types['image/gif'] = 'ImageCreateFromGIF';   
  204.         if (function_exists('ImageCreateFromPNG')) $gd_allow_types['image/png'] = 'ImageCreateFromPNG';   
  205.         if (function_exists('ImageCreateFromJPEG')) $gd_allow_types['image/jpeg'] = 'ImageCreateFromJPEG';   
  206.   
  207.         //获取文件信息   
  208.         $fileinfo = getImageSize($file);   
  209.         $wminfo   = getImageSize($this->watermark_file);   
  210.   
  211.         if ($fileinfo[0] < $wminfo[0] || $fileinfo[1] < $wminfo[1]) return;   
  212.   
  213.         if (array_key_exists($fileinfo['mime'],$gd_allow_types)) {   
  214.             if (array_key_exists($wminfo['mime'],$gd_allow_types)) {   
  215.                    
  216.                 //从文件创建图像   
  217.                 $temp = $gd_allow_types[$fileinfo['mime']]($file);   
  218.                 $temp_wm = $gd_allow_types[$wminfo['mime']]($this->watermark_file);   
  219.   
  220.                 //水印位置   
  221.                 switch ($this->watermark_pos) {                
  222.                     case 1 :  //顶部居左   
  223.                         $dst_x = 0; $dst_y = 0; break;                 
  224.                     case 2 :  //顶部居中   
  225.                         $dst_x = ($fileinfo[0] - $wminfo[0]) / 2; $dst_y = 0; break;                   
  226.                     case 3 :  //顶部居右   
  227.                         $dst_x = $fileinfo[0]; $dst_y = 0; break;                  
  228.                     case 4 :  //底部居左   
  229.                         $dst_x = 0; $dst_y = $fileinfo[1]; break;                  
  230.                     case 5 :  //底部居中   
  231.                         $dst_x = ($fileinfo[0] - $wminfo[0]) / 2; $dst_y = $fileinfo[1]; break;        
  232.                     case 6 :  //底部居右   
  233.                         $dst_x = $fileinfo[0]-$wminfo[0]; $dst_y = $fileinfo[1]-$wminfo[1]; break;   
  234.                     default : //随机   
  235.                         $dst_x = mt_rand(0,$fileinfo[0]-$wminfo[0]); $dst_y = mt_rand(0,$fileinfo[1]-$wminfo[1]);   
  236.                 }   
  237.   
  238.                 if (function_exists('ImageAlphaBlending')) ImageAlphaBlending($temp_wm,True); //设定图像的混色模式   
  239.                 if (function_exists('ImageSaveAlpha')) ImageSaveAlpha($temp_wm,True); //保存完整的 alpha 通道信息   
  240.   
  241.                 //为图像添加水印   
  242.                 if (function_exists('imageCopyMerge')) {   
  243.                     ImageCopyMerge($temp,$temp_wm,$dst_x,$dst_y,0,0,$wminfo[0],$wminfo[1],$this->watermark_trans);   
  244.                 } else {   
  245.                     ImageCopyMerge($temp,$temp_wm,$dst_x,$dst_y,0,0,$wminfo[0],$wminfo[1]);   
  246.                 }   
  247.   
  248.                 //保存图片   
  249.                 switch ($fileinfo['mime']) {   
  250.                     case 'image/jpeg' :   
  251.                         @imageJPEG($temp,$file);   
  252.                         break;   
  253.                     case 'image/png' :   
  254.                         @imagePNG($temp,$file);   
  255.                         break;   
  256.                     case 'image/gif' :    
  257.                         @imageGIF($temp,$file);   
  258.                         break;   
  259.                 }   
  260.                 //销毁零时图像   
  261.                 @imageDestroy($temp);   
  262.                 @imageDestroy($temp_wm);   
  263.             }   
  264.         }   
  265.     }   
  266.   
  267.     //获取文件扩展名   
  268.     function fileext($filename) {   
  269.         return strtolower(substr(strrchr($filename,'.'),1,10));   
  270.     }   
  271. }   
  272. ?>  

使用示例:

PHP代码
  1. <?php   
  2. if ($_GET['action'] == 'save') {   
  3.   
  4.     $up = new upload();   
  5.     $up->set_dir(dirname(__FILE__).'/upload/','{y}/{m}');   
  6.     $up->set_thumb(100,80);   
  7.     $up->set_watermark(dirname(__FILE__).'/jblog/images/watermark.png',6,90);   
  8.     $fs = $up->execute();   
  9.   
  10.     var_dump($fs);   
  11. }   
  12. ?>   
  13. <html>   
  14.     <head><title>test</title></head>   
  15.     <body style="margin:0;padding:0">   
  16.     <form name="upload" method="post" action="?action=save" enctype="multipart/form-data" style="margin:0">   
  17.         <input type="file" name="attach[]" />   
  18.         <input type="file" name="attach[]" />   
  19.         <input type="submit" name="submit" value="上 传" />   
  20.     </form>   
  21.     </body>   
  22. </html>  
标签:PHP JBLOG | 作者:admin | 分类:网站开发 | 评论: | 浏览: