一个处理图片上传问题的多功能PHP类(CLASS) 不指定

jed , 2006-10-3 08:28 , 代码编程 , 评论(0) , 阅读(3125) , Via 本站原创 | |

<?
class php_upload_class{

     var $FormName       = 'file'; //文件域名称
     var $Directroy      = './'; //上传至目录
     var $MaxSize        = 2097152; //最大上传大小
     var $CanUpload      = true; //是否可以上传
     var $doUpFile       = ''; //上传的文件名
     var $Error          = 0;  //错误参数
     var $user_post_file = array();  //用户上传的文件
     var $allow_type     = array('gif', 'jpg', 'png', 'bmp','txt','rar','zip','doc', 'pdf');
     var $save_info      = array(); //返回一组有用信息,用于提示用户。
     var $last_error     = '';
   var $mutiple_up_res = '';
   var $img_prefix     = 'p_';//重命名图片前缀
   var $is_same_name   = false; //是否将上传的文件重新名称,默认重名称
   var $custom_dir     = ''; //自定义图片名称
   
   var $to_remote      = false; //是否将上传的图片传到远程服务器
   var $host;                   //远程主机
   var $user;                   //用户名
   var $pw;                     //密码
   var $root_dir;              //远程路径
   
   var $is_zoom        = false; //是否将上传的图片文件生成缩略图,默认不缩放
     var $sm_File        = ''; //缩略图名称
     var $dscChar        = 'sm_';//缩略图名称前缀
   var $width          = 150;//缩略图宽度
   var $height         = 113;//缩略图高度
   
   var $is_watermark   = false; //是否将上传的图片文件打水印,默认不打水印
   var $quality        = 90; //0-100 生成图片质量
    var $errorMsg       = false; //水印处理错误
   var $waterPos       = 0; //水印起始位置
   var $waterImage     = ""; //水印图片路径
   var $waterText      = ""; //水印文字
   var $textFont       = 5; //水印文字大小
   var $textColor      = "#FF0000"; //水印文字颜色

   
     function php_upload_class($ini_array=array()){
             
        $this->user_post_file   = $ini_array['user_post_file'];
        $this->allow_type       = $ini_array['allow_type'];
        $this->is_same_name     = $ini_array['is_same_name'];
       
        $this->to_remote        = $ini_array['to_remote'];
        $this->host             = $ini_array['host'];
        $this->user             = $ini_array['user'];
        $this->pw               = $ini_array['pw'];
        $this->root_dir         = $ini_array['root_dir'];
       
        $this->is_zoom          = $ini_array['is_zoom'];
       
        $this->is_watermark     = $ini_array['is_watermark'];
        $this->waterPos         = $ini_array['waterPos'];
        $this->waterImage       = $ini_array['waterImage'];
        $this->waterText        = $ini_array['waterText'];
        $this->textFont         = $ini_array['textFont'];
        $this->textColor        = $ini_array['textColor'];
       
     }

    /*上传单个文件*/
     
     function upload_single_file($fileName = ''){
              if ($this->CanUpload){
                 if ($_FILES[$this->FormName]['size'] == 0){
                    $this->Error = 3;
                    $this->CanUpload = false;
                    return $this->Error;
                    break;
                 }
              }
 
              if($this->CanUpload){
 
                 if ($fileName == ''){
                     $fileName = $_FILES[$this->FormName]['name'];
                 }
     
                 $this->doUpload=@copy($_FILES[$this->FormName]['tmp_name'], $this->Directroy.$fileName);
 
                 if($this->doUpload){
                   $this->doUpFile = $fileName;
                   chmod($this->Directroy.$fileName, 0777);
                   return true;
                 }else{
                   $this->Error = 4;
                   return $this->Error;
                 }
              }
   
              //是否创建图片缩略图
              if($this->is_zoom){
         $imgInfo = @getimagesize($final_file_path);
         $srcWidth = $imgInfo[0];
         $srcHeight = $imgInfo[1];
         if($srcWidth>$srcHeight){
           $this->height = $srcHeight*$this->width/$srcWidth;
         }elseif($srcWidth<$srcHeight){
           $this->width = $srcWidth*$this->height/$srcHeight;
         }
       
        $this->thumb($this->dscChar,$this->width,$this->height);
              }
        //是否给图片加水印
              if($this->is_watermark){
         $this->imageWaterMark($fileName,$this->waterPos,$this->waterImage,$this->waterText,$this->textFont,$this->textColor);
        }
   
     }
     /*上传发生错误*/
   function parse_upload_error($last_error=0){
            switch($last_error){
               case "1":$last_error = "<li>上传的文件超过了 php.ini 中 upload_max_filesize 选项限制的值。</li>";break;
               case "2":$last_error = "<li>上传文件的大小超过了 HTML 表单中 MAX_FILE_SIZE 选项指定的值。</li>";break;
               case "3":$last_error = "<li>文件只有部分被上传。</li>";break;
               case "4":$last_error = "<li>没有文件被上传。</li>";break;
               default: $last_error = "";break;
        }
            return $last_error;
   }
   /* 上传多个文件  */
     
     function upload_mutiple_file() {
           
        if($this->to_remote){
          require("php_ftp_class.php");
 
              $ini_array = array();
                $ini_array['host']     = $this->host;
                 $ini_array['user']     = $this->user;
                 $ini_array['pw']       = $this->pw;
                 $ini_array['root_dir'] = $this->root_dir;
 
                  $ftp = new php_ftp_class($ini_array);
                  $ftp->connect();
        }
 
              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];
           $tmpname   = $this->user_post_file['tmp_name'][$i];
           $size      = $this->user_post_file['size'][$i];
           $mime_type = $this->user_post_file['type'][$i];
           $type      = $this->getExt($this->user_post_file['name'][$i]);
                   
                     if (!$this->checkSize($size)) {
            $this->last_error .= "<li>允许上传的文件最大值为:<b>".$this->get_real_size($this->MaxSize)."</b>,文件 <b>".$name."</b> 的大小为 <b>".$this->get_real_size($size)."</b> ,上传失败。<br>\n";
            continue;
                     }
                     
                     if (!$this->checkType($type)) {
            $this->last_error .= "<li><b>".$type."</b> 类型的文件不允许上传,<b>".$name."</b> 属于该类型,上传失败</li>";
                        continue;
                     }
                   
                    if(!@is_uploaded_file($tmpname)) {
            $this->last_error .= "<li>警告:文件 <b>".$name."</b>通过非正常渠道上传,上传失败。</li>";
            continue;
                    }
                   
                    $basename = $this->getBaseName($name, ".".$type);
         
          $saveas = $this->img_prefix.date("YmdHis").".".$type;
                    //是否重命名上传文件
          $saveas = $this->is_same_name ? $saveas : $name;
         
          //自定义图片名称
          $custom_dir = $this->custom_dir."/".date("YmdHis")."-".$this->get6random();
          $pathinfo = pathinfo($custom_dir);
          if($pathinfo['dirname']!="."){//自定义名称带有目录
            $pathinfo['dirname'] = (strpos($pathinfo['dirname'],"/")==0) ? substr($pathinfo['dirname'],1,strlen($pathinfo['dirname'])) : $pathinfo['dirname'];
            $pathinfo['dirname'] = str_replace("//","/",$pathinfo['dirname']);
            $dirs = explode("/",$pathinfo['dirname']);
            $dirname = false;
            if($i==0){
              foreach($dirs as $dir){
                     $dirname .= $dir."/";
                 $ftp->mk_dir($dirname,true);
              }
            }
            $ftp->root_dir = $ini_array['root_dir']."/".$pathinfo['dirname'];
          }

          $saveas = $this->custom_dir ? $custom_dir.".".$type : $saveas;
         
          $final_file_path = $this->Directroy."/".$saveas; //本地目录
                   
         
         //是否创建图片缩略图
         if($this->is_zoom){
           $this->CanUpload = true;
           $this->doUpFile  = $tmpname;
           $this->thumb($tmpname,basename($saveas),$this->dscChar,$this->width,$this->height);
           //上传缩略图到远程服务器
           
           if($this->to_remote){
             $ftp->ftp_put($this->dscChar.$this->sm_File,$this->sm_File);
           }else{
             if(!@move_uploaded_file($tmpname, $final_file_path)) {
             $this->last_error .= $this->parse_upload_error($this->user_post_file['error'][$i]);
             continue;
           }
           }
           @unlink($this->sm_File);
         }
         //是否给图片加水印
         if($this->is_watermark){
           $this->imageWaterMark($tmpname,$this->waterPos,$this->waterImage,$this->waterText,$this->textFont,$this->textColor);
         }
         //上传图片到服务器
          if($this->to_remote){
              $ftp->ftp_put(basename($saveas),$tmpname);
            if($ftp->error()){
              $this->last_error .= $ftp->error();
              continue;
            }
          }else{
            if(!@move_uploaded_file($tmpname, $final_file_path)) {
            $this->last_error .= $this->parse_upload_error($this->user_post_file['error'][$i]);
            continue;
            }
          }
                   //存储当前文件的有关信息,以便其它程序调用。
                   $this->save_info[] =  array("name"      => $name,
                                           "type"      => $type,
                                               "mime_type" => $mime_type,
                                               "size"      => $size,
                             "saveas"    => $saveas,
                                               "path"      => $final_file_path
                            );
                  }
              }
        if($this->to_remote){
          $ftp->close();
        }
              $this->mutiple_up_res  = '<ul>上传结果:<br>';
          $this->mutiple_up_res .= '有 <font color=green><b>'.count($this->save_info).'</b></font> 个文件被成功上传。<br>';
          if($this->last_error){
           // $this->mutiple_up_res .= '有 <font color=red><b>'.(count($this->user_post_file)-count($this->save_info)).'</b></font> 个文件上传失败。<br>';
            $this->mutiple_up_res .= '上传失败,详细如下:';
            $this->mutiple_up_res .= $this->last_error;
          }
          $this->mutiple_up_res .= '</ul>';
     
          return $this->mutiple_up_res; //返回上传结果信息
     }


     /*创建图片缩略图 */

     function thumb($srcFile,$dscFile,$dscChar='',$width=150,$height=113){

              if ($this->CanUpload && $this->doUpFile != ''){
                 $srcFile = $srcFile ? $srcFile : $this->doUpFile;
 
                 if ($dscChar == ''){
                     $dscChar = 'sm_';
                 }
           $dscFile = $dscFile ? $dscFile : $this->Directroy."/".$dscChar.$srcFile;
               
         $data    = getimagesize($srcFile);
 
                 switch ($data[2]) {
                        case 1:
                               $im = @imagecreatefromgif($srcFile);
                        break;
 
                        case 2:
                           $im = @imagecreatefromjpeg($srcFile);
                        break;
 
                        case 3:
                              $im = @imagecreatefrompng($srcFile);
                        break;
                }
           
        $srcWidth  = $data[0];
        $srcHeight = $data[1];
        if($srcWidth>$srcHeight){
           $width  = $this->width;
           $height = $srcHeight*$this->width/$srcWidth;
        }elseif($srcWidth<$srcHeight){
           $width  = $srcWidth*$this->height/$srcHeight;
         $height = $this->height;
        }else{
           $width  = $this->height;
         $height = $this->height;
        }
 
                $srcW=imagesx($im);
                $srcH=imagesy($im);
                $ni=imagecreatetruecolor($width,$height);
                imagecopyresized($ni,$im,0,0,0,0,$width,$height,$srcW,$srcH);
                $cr = imagejpeg($ni,$dscFile,$this->quality);
                @chmod($dscFile, 0777);

        if($cr){
          $this->sm_File = $dscFile;
         
          return true;
        }else{
          $this->last_error .= "<li>不能生成<b>&quot;".$dscFile."&quot;</b>的缩略图</li>";
          continue;
        }
              }
     
     }

     /* 功能:PHP图片水印 (水印支持图片或文字)
     * 参数:
     *      $groundImage    背景图片,即需要加水印的图片,暂只支持GIF,JPG,PNG格式;
     *      $waterPos        水印位置,有10种状态,0为随机位置;
     *                        1为顶端居左,2为顶端居中,3为顶端居右;
     *                        4为中部居左,5为中部居中,6为中部居右;
     *                        7为底端居左,8为底端居中,9为底端居右;
     *      $waterImage        图片水印,即作为水印的图片,暂只支持GIF,JPG,PNG格式;
     *      $waterText        文字水印,即把文字作为为水印,支持ASCII码,不支持中文;
     *      $textFont        文字大小,值为1、2、3、4或5,默认为5;
     *      $textColor        文字颜色,值为十六进制颜色值,默认为#FF0000(红色);
     *
     * 注意:Support GD 2.0,Support FreeType、GIF Read、GIF Create、JPG 、PNG
     *      $waterImage 和 $waterText 最好不要同时使用,选其中之一即可,优先使用 $waterImage。
     *      当$waterImage有效时,参数$waterString、$stringFont、$stringColor均不生效。
     *      加水印后的图片的文件名和 $groundImage 一样。
     * 作者:longware @ 2004-11-3 14:15:13 我修改的
     */
     function imageWaterMark($groundImage,$waterPos=0,$waterImage,$waterText,$textFont=5,$textColor="#FF0000"){

              $isWaterImage = FALSE;
              $formatMsg = "警告:暂不支持该文件格式,请用图片处理软件将图片转换为GIF、JPG、PNG格式。";

              //读取水印文件
              if(!empty($waterImage)) {
                $isWaterImage = TRUE;
                $water_info   = @getimagesize($waterImage);
                $water_w      = $water_info[0];//取得水印图片的宽
                $water_h      = $water_info[1];//取得水印图片的高

                switch($water_info[2]){ //取得水印图片的格式
                      case 1:$water_im = @imagecreatefromgif($waterImage);break;
                      case 2:$water_im = @imagecreatefromjpeg($waterImage);break;
                      case 3:$water_im = @imagecreatefrompng($waterImage);break;
                      default:
                    $this->errormsg = $formatMsg;
                    die("");
                break;
                }
              }

              //读取背景图片
              if($groundImage) {
                $ground_info = getimagesize($groundImage);
                $ground_w    = $ground_info[0];//取得背景图片的宽
                $ground_h    = $ground_info[1];//取得背景图片的高

                switch($ground_info[2]){//取得背景图片的格式  
                      case 1:$ground_im = imagecreatefromgif($groundImage);break;
                      case 2:$ground_im = imagecreatefromjpeg($groundImage);break;
                      case 3:$ground_im = imagecreatefrompng($groundImage);break;
                      default:
                $this->errorMsg = $formatMsg;
                    die("");
                break;
                }
              }else{
        $this->errorMsg = "需要加水印的图片不存在!";
                die("");
              }

              //水印位置
              if($isWaterImage){//图片水印  
                $w = $water_w;
                $h = $water_h;
                $label = "图片的";
              }else{ //文字水印  
                $temp = imagettfbbox(ceil($textFont*2.5),0,"./ARIAL.TTF",$waterText);//取得使用 TrueType 字体的文本的范围
                $w = $temp[2] - $temp[6];
                $h = $temp[3] - $temp[7];
                unset($temp);
                $label = "文字区域";
              }
              if( ($ground_w<$w) || ($ground_h<$h) ){
                $this->errorMsg = "需要加水印的图片的长度或宽度比水印".$label."还小,无法生成水印!";
                return;
              }
              switch($waterPos) {
                    case 0://随机
                           $posX = rand(0,($ground_w - $w));
                           $posY = rand(0,($ground_h - $h));
                           break;
                    case 1://1为顶端居左
                           $posX = 0;
                           $posY = 0;
                           break;
                    case 2://2为顶端居中
                           $posX = ($ground_w - $w) / 2;
                           $posY = 0;
                           break;
                    case 3://3为顶端居右
                           $posX = $ground_w - $w;
                           $posY = 0;
                           break;
                    case 4://4为中部居左
                           $posX = 0;
                           $posY = ($ground_h - $h) / 2;
                           break;
                    case 5://5为中部居中
                           $posX = ($ground_w - $w) / 2;
                           $posY = ($ground_h - $h) / 2;
                           break;
                    case 6://6为中部居右
                           $posX = $ground_w - $w;
                           $posY = ($ground_h - $h) / 2;
                           break;
                    case 7://7为底端居左
                           $posX = 0;
                          $posY = $ground_h - $h;
                           break;
                    case 8://8为底端居中
                           $posX = ($ground_w - $w) / 2;
                           $posY = $ground_h - $h;
                           break;
                    case 9://9为底端居右
                           $posX = $ground_w - $w;
                           $posY = $ground_h - $h;
                           break;
                    case 10://自定义
                           $posX = 160;
                           $posY = 265;
                           break;    
                    default://随机
                           $posX = rand(0,($ground_w - $w));
                           $posY = rand(0,($ground_h - $h));
                           break;
              }

              //设定图像的混色模式
              imagealphablending($ground_im, true);

              if($isWaterImage){ //图片水印  
                imagecopy($ground_im, $water_im, $posX, $posY, 0, 0, $water_w,$water_h);//拷贝水印到目标文件        
              }else{//文字水印
                if( !empty($textColor) && (strlen($textColor)==7) ){
                    $R = hexdec(substr($textColor,1,2));
                    $G = hexdec(substr($textColor,3,2));
                    $B = hexdec(substr($textColor,5));
                }else{
          $this->errorMsg = "水印文字颜色格式不正确!";
                    die("");
                }
                imagestring ( $ground_im, $textFont, $posX, $posY, $waterText, imagecolorallocate($ground_im, $R, $G, $B));        
              }

              //生成水印后的图片
              @unlink($groundImage);
              switch($ground_info[2]){ //取得背景图片的格式
                    case 1:imagegif($ground_im,$groundImage);break;
                    case 2:imagejpeg($ground_im,$groundImage,$this->quality);break;
                    case 3:imagepng($ground_im,$groundImage);break;
                    default:
              $this->errorMsg = '不支持该类型背景图片';
                  die("");
              break;
             }

              //释放内存
              if(isset($water_info)) unset($water_info);
              if(isset($water_im)) imagedestroy($water_im);
              unset($ground_info);
              imagedestroy($ground_im);
     }
     //检查文件是否存在
     function scanFile()
     {
              if ($this->CanUpload){
                 $scan = is_readable($_FILES[$this->FormName]['name']);
                 if ($scan){  
                    $this->Error = 2;
                 }
                 return $scan;
             }
     }

     //获取文件大小
     function getSize($format = 'B')
     {
 
              if ($this->CanUpload)
        {
 
                  if ($_FILES[$this->FormName]['size'] == 0){
                      $this->Error = 3;
                      $this->CanUpload = false;
                  }
 
                  switch ($format){
                         case 'B':
                                  return $_FILES[$this->FormName]['size'];
                         break;
 
                         case 'M':
                                  return ($_FILES[$this->FormName]['size'])/(1024*1024);
             break;
                  }
 
               }
      }
      //转换大小
      function get_real_size($size) {

               $kb = 1024;         // Kilobyte
               $mb = 1024 * $kb;   // Megabyte
               $gb = 1024 * $mb;   // Gigabyte
               $tb = 1024 * $gb;   // Terabyte

               if($size < $kb) {
                  return $size." B";
               }else if($size < $mb) {
                  return round($size/$kb,2)." KB";
               }else if($size < $gb) {
                  return round($size/$mb,2)." MB";
               }else if($size < $tb) {
                  return round($size/$gb,2)." GB";
               }else {
                  return round($size/$tb,2)." TB";
               }

       }

     //获取文件类型
     function getExt($filename=false)
     {
           if($filename){
               $stuff = pathinfo($filename);
               return $stuff['extension'];
       }else{
               if ($this->CanUpload){
                  $ext=$_FILES[$this->FormName]['name'];
                  $extStr=explode('.',$ext);
                  $count=count($extStr)-1;
               }
               return $extStr[$count];
       }
     }

     //获取文件名称
     function getName()
     {
              if ($this->CanUpload){
                 return $_FILES[$this->FormName]['name'];
              }
     }

     //新建文件名
     function newName()
     {
             if ($this->CanUpload){
                $FullName=$_FILES[$this->FormName]['name'];
                $extStr=explode('.',$FullName);
                $count=count($extStr)-1;
                $ext = $extStr[$count];
 
                return date('YmdHis').rand(0,9).'.'.$ext;
             }
    }

      //显示错误参数
      function Err(){
               return $this->Error;
      }

     //上传后的文件名
     function UpFile(){

              if ($this->doUpFile != ''){
                 return $this->doUpFile;
              }else{
                 $this->Error = 6;
              }
    }

     //上传文件的路径
     function filePath(){

              if ($this->doUpFile != ''){
                 return $this->Directroy.$this->doUpFile;
             }else{
                 $this->Error = 6;
             }  
     }

     //缩略图文件名称
     function thumbMap(){

              if ($this->sm_File != ''){
                 return $this->sm_File;
              }else{
                $this->Error = 6;
              }
     }
    //////////////////extention
     /**//**
     * 检测用户提交文件类型是否合法
     * @access private
     * @return boolean 如果为true说明类型合法,反之不合法
     */
     function checkType($extension) {
              foreach ($this->allow_type as $type) {
                      if (strcasecmp($extension , $type) == 0)
                      return true;
              }
              return false;
     }


     /**//**
     * 取给定文件文件名,不包括扩展名。
     * eg: getBaseName("j:/hexuzhong.jpg"); //返回 hexuzhong
     *
     * @param String $filename 给定要取文件名的文件
     * @access private
     * @return String 返回文件名
     */

     function getBaseName($filename, $type) {
              $basename = basename($filename, $type);
              return $basename;
     }
   function halt($msg) {
            return $msg;
   }
   /**//**
     * 检测用户提交文件大小是否合法
     * @param Integer $size 用户上传文件的大小
     * @access private
     * @return boolean 如果为true说明大小合法,反之不合法
     */
    function checkSize($size) {
     
           if ($size > $this->MaxSize ) {
                return false;
             }
             else {
                return true;
             }
     }
     
    function get6random(){
             $return = false;
         $str = "1 2 3 4 5 6 7 8 9";
         $arr = explode(" ",$str);
         srand((double)microtime()*1000000);
       
         for($i=0;$i<=6;$i++){
            $salt = rand(0, 9);
          $return .= $arr[$salt];
         }
         return $return;
    }



}

////////////////////////////测试
/*
echo '
<form action="" method="post" enctype="multipart/form-data" name="form1">
<input type="file" name="file[]"><br>
<input type="file" name="file[]"><br>
<input type="file" name="file[]"><br>
<input type="file" name="file[]"><br>
<input type="file" name="file[]"><br>
<input type="file" name="file[]"><br>
<input type="submit" name="Submit" value="提交">
<input name="scan" type="hidden" id="up" value="true">
</form>
';
if(!empty($_POST['scan'])){
       
 
 require("config.php");
 require("php_ftp_class.php");
 $ini_array = array();
 *//*
 $settings['FTP_HOST']='192.168.1.8';
 $settings['FTP_USER']='program';
 $settings['FTP_PW']='k8c3321d';
 $settings['FTP_ROOT_DIR']='E:/web/program/product';
 *//*
 $ini_array['host']             = $settings['FTP_HOST'];
 $ini_array['user']             = $settings['FTP_USER'];
 $ini_array['pw']               = $settings['FTP_PW'];
 $ini_array['root_dir']         = $settings['FTP_ROOT_DIR'];

 $ini_array['remote_host_path'] = "http://192.168.1.8/";
 $ini_array['user_post_file']   = $_FILES['file'];
 $ini_array['allow_type']       = array('gif', 'jpg', 'png', 'bmp');

 $ini_array['is_zoom']          = true;//需要生成缩略图
 
 
 $ini_array['is_watermark']     = true;//需要加水印
 $ini_array['waterPos']         = 5 ; //缺省为随机//0为随机 //1为顶端居左 //2为顶端居中 //3为顶端居右 //4为中部居左 //5为中部居中 //6为中部居右 //7为底端居左 //8为底端居中 //9为底端居右
 $ini_array['waterImage']       = "./tmpfolder/angel.gif"; //水印图片
 $ini_array['waterText']        = "";
 $ini_array['textFont']         = 6;
 $ini_array['textColor']        = "#ff0000";

 $ini_array['is_same_name']     = 1;//不需要重命名上传文件

 $upfos = new php_upload_class($ini_array);
 
 $tmpfolder = "./tmpfolder";
 
 if(!file_exists($tmpfolder)) mkdir($tmpfolder, 0777);
 
 $upfos->Directroy  = $tmpfolder;

 $upfos->upload_mutiple_file();

 echo $upfos->mutiple_up_res;
 
 foreach($upfos->save_info as $fileInfo){
     echo '<iframe src="ftp_put.php?to='.$fileInfo['saveas'].'&from='.$fileInfo['path'].'" frameborder="0" height="0" width="0" scrolling="no" ></iframe>';
     if($upfos->is_zoom) {
       echo '<iframe src="ftp_put.php?to=p_small/'.$upfos->dscChar.$fileInfo['saveas'].'&from='.dirname($fileInfo['path'])."/".$upfos->dscChar.$fileInfo['saveas'].'" frameborder="0" height="0" width="0" scrolling="no" ></iframe>';
     }
 }

// if($upfos->is_zoom) echo "<img src='{$tmpfolder}/sm_".$upfos->save_info[0]['name']."'><br>";
 
// echo "<img src='{$tmpfolder}/".$upfos->save_info[0]['name']."'>";

}
*/
?>
以上程序运行必要文件。
php_ftp_class.php

<?
class php_ftp_class{
     var $user     ;
     var $pw       ;
     var $host     ;
     var $root_dir = "";//root ftp dir of server
     var $con_id   = 0;//descriptor on ftp connection
     var $cwd;//current working dir
     var $FTP_MODE = 'FTP_BINARY';// FTP_ASCII | FTP_BINARY
     var $ERR      = false;//must object display ftp errors
     //constr.
     function php_ftp_class($ini_array=array('host'=>"localhost",'user'=>"guest",'pw'=>"guest",'root_dir'=>"",'remote_path'=>'http://localhost')){
              $this->host     = $ini_array['host'];
          $this->user     = $ini_array['user'];
          $this->pw       = $ini_array['pw'];
          $this->root_dir = $ini_array['root_dir'];
         
              if($this->connect()){
                 $this->cwd = @ftp_pwd($this->con_id); //返回当前目录名
              }
     }

     //connect to ftp server
     function connect(){
              $this->con_id = @ftp_connect($this->host);
              if(!$this->con_id){
   
               $this->ERR .= "<li>尝试连接到远程主机".$this->host."时发生错误,连接失败</li>";  
               return false;
 
            }
            if(@ftp_login($this->con_id,$this->user,$this->pw)){
       
             return true;
       
          }else{
       
            $this->ERR .= "<li>用户名 <b>&quot;".$this->user."&quot;</b> 错误,不能登录到远端主机 <b>&quot;".$this->host."&quot;</b>,登录失败</li>";
       
          }
            return false;
     }

     //close ftp connection
     function close(){
              ftp_quit($this->con_id);
     }

     //print error messages
     function error(){
              return   $this->ERR ? "<ul>FTP错误:".$this->ERR."</ul>\n" : false;
     }

     //change current working dir
     function cd($dir){
              if(!@ftp_chdir($this->con_id,$dir)){
                $this->ERR .= "<li>Cannot view directory <b>&quot;".$this->root_dir."/".$dir."&quot;</b>!</li>";
                return false;
              }
              $this->cwd=@ftp_pwd($this->con_id);
              return true;
     }

     //create new empty file
     function mk_file($name){
                if(!$tmpfile=tempnam("/tmp","phpftptmp")){
                  $this->ERR .= "<li>Can't create temp file?</li>";
                  return false;
                }elseif(!ftp_put($this->con_id,$name,$tmpfile,$this->FTP_MODE)){
                   $this->ERR .= "<li>Can't create file <b>&quot;".$this->root_dir."/".$this->cwd."/".$name."&quot;</b></li>";
                   unlink($tmpfile);
                   return false;
                }
                unlink($tmpfile);
                return true;
     }

     //create new dir
     function mk_dir($dir_name,$ret=false){
              $mkdir = @ftp_mkdir($this->con_id,$this->root_dir."/".$this->cwd."/".$dir_name);
        if (!$mkdir && !$ret){
         $this->ERR .= "<li>不能创建文件夹 <b>&quot;".$this->root_dir.$this->cwd.$dir_name."&quot;</b></li>";
         return false;
              }
              return true;
     }

     //change access right to object
     function set_perm($obj,$num){
              //CHMOD 444 ftp.php3
              if(!$this->site("CHMOD ".$num." ".$obj)){
                $this->ERR .= "<li>Cannot change permitions of object <b>&quot;".$this->root_dir."/".$this->cwd."/".$obj."&quot;</b></li>";
                return false;
              }
              return true;
     }

     //send SITE command
     function site($cmd){
              if(!ftp_site($this->con_id, $cmd)){
                $this->ERR .= "<li>Cannot send site command <b>&quot;".$cmd."&quot;</b></li>";
                return false;
              }
              return true;
 }

     //copy file D:/web/images.imp3.net/upload/product $ftp->copy("./images/upload_success.gif","upload_success.gif",true);
     function copy($from,$to){
   /*
 if(file_exists($this->root_dir."/".$to)){
     $this->error("Object <b>&quot;".$this->root_dir."/".$to."&quot;</b> already exists!");
     return false;
   }
   srand((double)microtime()*1000000);
   $tmpfile= dirname(tempnam('',''))."/phpftptmp.".rand() ;
   */
            if(!copy($from,$to)){
                $this->ERR .= "<li>上传<b>&quot;$from&quot;</b>到<b>&quot;$this->root_dir/$to&quot;</b>失败!</li>";
                return false;
              }
              return true;
     }
     function ftp_put($remote_file,$local_file,$ftp_mode=false){
   /*
 if(file_exists($this->root_dir."/".$to)){
     $this->error("Object <b>&quot;".$this->root_dir."/".$to."&quot;</b> already exists!");
     return false;
   }
   */
 //FTP_BINARY为什么不能用变量代替???
            if(!$ftp_mode){
                if(!ftp_put($this->con_id,$this->root_dir."/".$remote_file,$local_file,FTP_BINARY)){
                  $this->ERR .= "<li>上传<b>&quot;$local_file&quot;</b>到<b>&quot;$this->root_dir/$remote_file&quot;</b>失败!</li>";
                  return false;
                }
            }else{
                if(!ftp_put($this->con_id,$this->root_dir."/".$remote_file,$local_file,FTP_ASCII)){
                  $this->ERR .= "<li>上传<b>&quot;$local_file&quot;</b>到<b>&quot;$this->root_dir/$remote_file&quot;</b>失败!</li>";
                  return false;
               }
            }
            return true;
     }
     //move object
     function move($from,$to){
              if(!@ftp_rename($this->con_id,$this->root_dir."/".$from,$this->root_dir."/".$to)){
                $this->ERR .= "<li>移动 <b>&quot;".$this->root_dir."/".$from."&quot;</b> 到 <b>&quot;".$this->root_dir."/".$to."&quot;失败!</b></li>";
                return false;
              }
              return true;
     }

     //rename object
     function rename($from,$to){
              if(!@ftp_rename($this->con_id,$this->root_dir."/".$this->cwd."/".$from,$this->root_dir."/".$this->cwd."/".$to)){
                $this->ERR .= "<li>Cannot rename object <b>&quot;".$this->root_dir."/".$this->cwd."/".$to."&quot;</b></li>";
                return false;
              }
              return true;
     }

     //delete directory  
     function delete_dir($dir){
              if(!@ftp_rmdir($this->con_id, $this->root_dir."/".$this->cwd."/".$dir)){
                $this->ERR .= "<li>不能删除远端文件夹 <b>&quot;".$this->root_dir."/".$dir."&quot;</b></li>";
                return false;
              }
              return true;  
     }
     //delte file
     function delete_file($file){
   
              if(!@ftp_delete($this->con_id, $this->root_dir."/".$this->cwd."/".$file)){
                $this->ERR .= "<li>不能删除远端文件 <b>&quot;".$this->root_dir."/".$file."&quot;</b></li>";
        return false;
              }
              return true;  
     }

     //write into file
     function write($dest,$FILEDATA){
              if(!WIN){
               $old_perm=$this->get_perm($dest,'i');
               $this->set_perm($dest,"666");
             }
             $fd=fopen($this->root_dir."/".$this->cwd."/".$dest,"w");
             if(!fwrite($fd,$FILEDATA)){
               $this->ERR .= "<li>Cannot write file <b>&quot;".$this->root_dir."/".$this->cwd."/".$dest."&quot;</b></li>";
               fclose($fd);
               if(!WIN)$this->set_perm($dest,"644");
               return false;
             }
             fclose($fd);
             if(!WIN)$this->set_perm($dest,"644");
             return true;
     }

     //move uploaded file from TMP into CWD
     function move_uploaded_file($file_to_move,$file_name){
              srand((double)microtime()*1000000);
             if(!$tmp_dir=get_cfg_var('upload_tmp_dir'))$tmp_dir=dirname(tempnam('',''));
             $tmpfile=$tmp_dir."/phpftptmp.".rand();
             if(!copy($file_to_move,$tmpfile)){
               $this->ERR .=  "<li>Can't create temp file?</li>";
               unlink($file_to_move);
               return false;
             }elseif(!ftp_put($this->con_id,$this->cwd."/".$file_name,$tmpfile,$this->FTP_MODE)){
               $this->ERR .= "<li>Can't write file <b>&quot;".$this->root_dir."/".$this->cwd."/".$file_name."&quot;</b></li>";
               unlink($file_to_move);
               unlink($tmpfile);
               return false;
             }
             unlink($file_to_move);
             unlink($tmpfile);
             return true;
     }

     //return access right of an object, at various formats
     function get_perm($obj,$type='i'){
              $num=fileperms($obj);
             $s=array(07=>'rwx',06=>'rw-',05=>'r-x',04=>'r--',03=>'-wx',02=>'-w-',01=>'--x',00=>'---');
             $i=array(07=>'7',06=>'6',05=>'5',04=>'4',03=>'3',02=>'2',01=>'1',00=>'0');
             $b=array(
               07=>array(1,1,1),
               06=>array(1,1,0),
               05=>array(1,0,1),
               04=>array(1,0,0),
               03=>array(0,1,1),
               02=>array(0,1,0),
               01=>array(0,0,1),
               00=>array(0,0,0)
             );
             switch($type){
               case 'b':
                 $ret['o']=$b[($num & 0700)>>6];
                 $ret['g']=$b[($num &  070)>>3];
                 $ret['a']=$b[($num &   07)   ];
                 break;
               case 's':

                 if($num & 0x1000)     $ret ='p';//FIFO pipe
                 elseif($num & 0x2000) $ret.='c';//Character special
                 elseif($num & 0x4000) $ret.='d';//Directory
                 elseif($num & 0x6000) $ret.='b';//Block special
                 elseif($num & 0x8000) $ret.='-';//Regular
                 elseif($num & 0xA000) $ret.='l';//Symbolic Link
                 elseif($num & 0xC000) $ret.='s';//Socket
                 else $str.='?'; //UNKNOWN
                 $ret.=$s[($num & 0700)>>6];
                 $ret.=$s[($num &  070)>>3];
                 $ret.=$s[($num &   07)   ];
                 break;
               case 'i':
                 $ret =$i[($num & 0700)>>6];
                 $ret.=$i[($num &  070)>>3];
                 $ret.=$i[($num &   07)   ];
                 break;
             }
             return $ret;
     }
   //这里显示方式可以按自己的方法修改
     //print dir file list
     function dir_list(){
   //ftp_nlist ?Returns a list of files in the given directory.
   //ftp_rawlist ?Returns a detailed list of files in the given directory.
            $dir_list = '
            <table border=1 cellpadding=3 cellspacing=0><tr><td>Directories</td><td>Files</td></tr>';
            $contents=ftp_nlist($this->con_id, $this->cwd);
            $d_i=0;
            $f_i=0;
            sort($contents);
            for($i=0;$i<count($contents);$i++){
              $file_size=ftp_size($this->con_id,$contents[$i]);
              if(is_dir($this->root_dir.$contents[$i])){
                $nlist_dirs[$d_i]=$contents[$i];
                $d_i++;
              }else{
                $nlist_files[$f_i]=$contents[$i];
                $nlist_filesize[$f_i]=$file_size;
                $f_i++;
              }
            }
           $dir_list .='<tr><td><pre>';
            for($i=0;$i<count($nlist_dirs);$i++)
             $dir_list .=$nlist_dirs[$i]."<br>";
            $dir_list .='</td><td><pre>';
            for($i=0;$i<count($nlist_files);$i++)
             $dir_list .=$nlist_files[$i]." ".(int)$nlist_filesize[$f_i]."<br>";
            $dir_list .='</td></tr></table>';
          return $dir_list;
     }
}
/*测试
    require("config.php");

    $FTP_HOST=$settings['FTP_HOST'];
    $FTP_USER=$settings['FTP_USER'];
    $FTP_PW=$settings['FTP_PW'];
    $FTP_ROOT_DIR=$settings['FTP_ROOT_DIR'];
    $ftp = new php_ftp_class($FTP_USER,$FTP_PW,$FTP_HOST,$FTP_ROOT_DIR);
    $ftp->connect();
        $ftp->ftp_put("upload_success.gif","./images/upload_success.gif");
    $ftp->close();
    $ftp->error();*/


?>
发表评论

昵称

网址

电邮

打开HTML 打开UBB 打开表情 隐藏 记住我 [登入] [注册]