日韩亚洲AV无码一区二区三区|av在线国产哟哟|国产精品人人爽人人爽AV|免费一区二区精品无码视频

<th id="kwciy"><video id="kwciy"></video></th>
<code id="kwciy"><em id="kwciy"><optgroup id="kwciy"></optgroup></em></code>
    1. <center id="kwciy"></center>

      <code id="kwciy"></code>

      0712-2888027 189-8648-0214
      微信公眾號

      孝感風信網(wǎng)絡科技有限公司微信公眾號

      當前位置:主頁 > 技術支持 > PHP > 一個經(jīng)典的PHP文件上傳類fileupload.class.php分享

      一個經(jīng)典的PHP文件上傳類fileupload.class.php分享

      時間:2018-10-23來源:風信官網(wǎng) 點擊: 733次
      一、需求分析

        要球自定義文件上傳類,即在使用非常簡便的前提下,又可以完成以下幾項功能:
       ?、僦С謫蝹€文件上傳。
       ?、谥С侄鄠€文件上傳。
        ③可以自己指定上傳文件的保存位置,可以設置上傳文件允許的大小和類型,可以由系統(tǒng)對上傳文件重新命名,又可以設置保留上傳文件的原名。
       ?。ㄕf明:要求單個文件上傳和多個文件上傳要采用同樣的操作方式,對上傳進行的一些設置也要采用相同的方式)。

      二、程序設計

        根據(jù)程序需求的要求,我們可以為文件上傳類聲明4個可見的成員屬性,讓用戶在使用時還可以進行一些行為的設置。需要的成員屬性如下表所示:

        為避免屬性的值被賦上一些非法值,需要將這些成員屬性封裝起來,在對象外面不能訪問,再通過類中聲明的set()方法為以上四個成員屬性賦值。set()方法有兩個參數(shù),第一個參數(shù)就是成員屬性名稱(不區(qū)分大小寫),第二個參數(shù),就是前面參數(shù)中屬性對應的值。set()方法調(diào)用完成以后,返回本對象($this),所以除了可以單獨為每個屬性賦值以外,還可以進行連貫操作一起為多個屬性賦值。本例中除了set()方法以外,最主要的是實現(xiàn)上傳文件的功能,所以系統(tǒng)主要提供了以下一些公有方法,實現(xiàn)文件上傳的操作,如下表所示:

      <?php
       /**
       * Created by PhpStorm.
       * User: Sunco
       * Date: 2018/10/23
       * Time: 9:23
       * file: fileupload.class.php 文件上傳類FileUpload
       * 本類的實例對象用于處理上傳文件,可以上傳一個文件,也可同時處理多個文件上傳
       */
      class FileUpload
      {
          private $path = "./file/upload/";          //上傳文件保存的路徑
          private $allowtype = array('jpg', 'gif', 'png'); //設置限制上傳文件的類型
          private $maxsize = 1000000;           //限制文件上傳大小(字節(jié))
          private $israndname = true;           //設置是否隨機重命名文件, false不隨機
       
          private $originName;              //源文件名
          private $tmpFileName;              //臨時文件名
          private $fileType = "jpg";               //文件類型(文件后綴)
          private $fileSize;               //文件大小
          private $newFileName;              //新文件名
          private $errorNum = 0;             //錯誤號
          private $errorMess = "";             //錯誤報告消息
       
          /**
           * 用于設置成員屬性($path, $allowtype,$maxsize, $israndname)
           * 可以通過連貫操作一次設置多個屬性值
           * @param  string $key 成員屬性名(不區(qū)分大小寫)
           * @param  mixed  $val 為成員屬性設置的值
           * @return  object     返回自己對象$this,可以用于連貫操作
           */
          function set($key, $val)
          {
              $key = strtolower($key);
              if (array_key_exists($key, get_class_vars(get_class($this)))) {
                  $this->setOption($key, $val);
              }
              return $this;
          }
       
          /**
           * 調(diào)用該方法上傳文件
           * @param  string $fileFile 上傳文件的表單名稱
           * @return bool        如果上傳成功返回數(shù)true
           */
       
          function upload($fileField)
          {
              $return = true;
              /* 檢查文件路徑是滯合法 */
              if (!$this->checkFilePath()) {
                  $this->errorMess = $this->getError();
                  return false;
              }
              /* 將文件上傳的信息取出賦給變量 */
              $name =$fileField['file']['name'];
              $tmp_name = $fileField['file']['tmp_name'];
              $size = $fileField['file']['size'];
              $error = $fileField['file']['error'];
              /* 如果是多個文件上傳則$file["name"]會是一個數(shù)組 */
              if (is_Array($name)) {
                  $errors = array();
                  /*多個文件上傳則循環(huán)處理 , 這個循環(huán)只有檢查上傳文件的作用,并沒有真正上傳 */
                  for ($i = 0; $i < count($name); $i++) {
                      /*設置文件信息 */
                      if ($this->setFiles($name[$i], $tmp_name[$i], $size[$i], $error[$i])) {
                          if (!$this->checkFileSize() || !$this->checkFileType()) {
                              $errors[] = $this->getError();
                              $return = false;
                          }
                      } else {
                          $errors[] = $this->getError();
                          $return = false;
                      }
                      /* 如果有問題,則重新初使化屬性 */
                      if (!$return)
                          $this->setFiles();
                  }
       
                  if ($return) {
                      /* 存放所有上傳后文件名的變量數(shù)組 */
                      $fileNames = array();
                      /* 如果上傳的多個文件都是合法的,則通過銷魂循環(huán)向服務器上傳文件 */
                      for ($i = 0; $i < count($name); $i++) {
                          if ($this->setFiles($name[$i], $tmp_name[$i], $size[$i], $error[$i])) {
                              $this->setNewFileName();
                              if (!$this->copyFile()) {
                                  $errors[] = $this->getError();
                                  $return = false;
                              }
                              $fileNames[] = $this->newFileName;
                          }
                      }
                      $this->newFileName = $fileNames;
                  }
                  $this->errorMess = $errors;
                  return $return;
                  /*上傳單個文件處理方法*/
              } else {
                  /* 設置文件信息 */
                  if ($this->setFiles($name, $tmp_name, $size, $error)) {
                      /* 上傳之前先檢查一下大小和類型 */
                      if ($this->checkFileSize() && $this->checkFileType()) {
                          /* 為上傳文件設置新文件名 */
                          $this->setNewFileName();
                          /* 上傳文件  返回0為成功, 小于0都為錯誤 */
                          if ($this->copyFile()) {
                              return true;
                          } else {
                              $return = false;
                          }
                      } else {
                          $return = false;
                      }
                  } else {
                      $return = false;
                  }
                  //如果$return為false, 則出錯,將錯誤信息保存在屬性errorMess中
                  if (!$return)
                      $this->errorMess = $this->getError();
       
                  return $return;
              }
          }
       
          /**
           * 獲取上傳后的文件名稱
           * @param  void   沒有參數(shù)
           * @return string 上傳后,新文件的名稱, 如果是多文件上傳返回數(shù)組
           */
          public function getFileName()
          {
              return $this->newFileName;
          }
       
          /**
           * 上傳失敗后,調(diào)用該方法則返回,上傳出錯信息
           * @param  void   沒有參數(shù)
           * @return string  返回上傳文件出錯的信息報告,如果是多文件上傳返回數(shù)組
           */
          public function getErrorMsg()
          {
              return $this->errorMess;
          }
       
          /* 設置上傳出錯信息 */
          private function getError()
          {
              $str = "上傳文件<font color='red'>{$this->originName}</font>時出錯 : ";
              switch ($this->errorNum) {
                  case 4:
                      $str .= "沒有文件被上傳";
                      break;
                  case 3:
                      $str .= "文件只有部分被上傳";
                      break;
                  case 2:
                      $str .= "上傳文件的大小超過了HTML表單中MAX_FILE_SIZE選項指定的值";
                      break;
                  case 1:
                      $str .= "上傳的文件超過了php.ini中upload_max_filesize選項限制的值";
                      break;
                  case -1:
                      $str .= "未允許類型";
                      break;
                  case -2:
                      $str .= "文件過大,上傳的文件不能超過{$this->maxsize}個字節(jié)";
                      break;
                  case -3:
                      $str .= "上傳失敗";
                      break;
                  case -4:
                      $str .= "建立存放上傳文件目錄失敗,請重新指定上傳目錄";
                      break;
                  case -5:
                      $str .= "必須指定上傳文件的路徑";
                      break;
                  default:
                      $str .= "未知錯誤";
              }
              return $str . '<br>';
          }
       
          /* 設置和$_FILES有關的內(nèi)容 */
          private function setFiles($name = "", $tmp_name = "", $size = 0, $error = 0)
          {
              $this->setOption('errorNum', $error);
              if ($error)
                  return false;
              $this->setOption('originName', $name);
              $this->setOption('tmpFileName', $tmp_name);
              $aryStr = explode(".", $name);
              $this->setOption('fileType', strtolower($aryStr[count($aryStr) - 1]));
              $this->setOption('fileSize', $size);
              return true;
          }
       
          /* 為單個成員屬性設置值 */
          private function setOption($key, $val)
          {
              $this->$key = $val;
          }
       
          /* 設置上傳后的文件名稱 */
          private function setNewFileName()
          {
              if ($this->israndname) {
                  $this->setOption('newFileName', $this->proRandName());
              } else {
                  $this->setOption('newFileName', $this->originName);
              }
          }
       
          /* 檢查上傳的文件是否是合法的類型 */
          private function checkFileType()
          {
              if (in_array(strtolower('jpg'), $this->allowtype)) {
                  return true;
              } else {
                  $this->setOption('errorNum', -1);
                  return false;
              }
          }
       
          /* 檢查上傳的文件是否是允許的大小 */
          private function checkFileSize()
          {
              if ($this->fileSize > $this->maxsize) {
                  $this->setOption('errorNum', -2);
                  return false;
              } else {
                  return true;
              }
          }
       
          /* 檢查是否有存放上傳文件的目錄 */
          private function checkFilePath()
          {
              if (empty($this->path)) {
                  $this->setOption('errorNum', -5);
                  return false;
              }
              if (!file_exists($this->path) || !is_writable($this->path)) {
                  if (!@mkdir($this->path, 0755)) {
                      $this->setOption('errorNum', -4);
                      return false;
                  }
              }
              return true;
          }
       
          /* 設置隨機文件名 */
          private function proRandName()
          {
              $fileName = date('YmdHis') . "_" . rand(100, 999);
              return $fileName . '.' . $this->fileType;
          }
       
          /* 復制上傳文件到指定的位置 */
          private function copyFile()
          {
              if (!$this->errorNum) {
                  $path = rtrim($this->path, '/') . '/';
                  $path .= $this->newFileName;
                  if (@move_uploaded_file($this->tmpFileName, $path)) {
                      return true;
                  } else {
                      $this->setOption('errorNum', -3);
                      return false;
                  }
              } else {
                  return false;
              }
          }
      }
       
      ?>

      四、文件上傳類的應用過程

        本例的文件上傳類FileUpload,即支持單文件上傳,也支持多個文件一起向服務器上傳,在處理方式上沒有區(qū)別的,只不過在編寫上傳標單時,多個文件上傳一定要以數(shù)組方式傳遞給服務器。單個文件上傳表單如下所示:
      
      <form action="upload.php" method="post" enctype="multipart/form-data" >
          name: <input type="text" name="username" value="" /><br>
          <input type="hidden" name="MAX_FILE_SIZE" value="1000000" />
          up pic: <input type="file" name="pic[]" value=""><br>
          up pic: <input type="file" name="pic[]" value=""><br>
          up pic: <input type="file" name="pic[]" value=""><br>
          up pic: <input type="file" name="pic[]" value=""><br>
        
          <input type="submit" value="upload" /><br>  
      </form>


      上面表單,都將提交的位置指向了同一個文件upload.php,所以不難看出單個和多個文件上傳是一樣的處理方式,upload.php代碼如下所示:

      <?php
          //包含一個文件上傳類中的上傳類
          include "fileupload.class.php";
       
          $up = new fileupload;
          //設置屬性(上傳的位置, 大小, 類型, 名是是否要隨機生成)
          $up -> set("path", "./images/");
          $up -> set("maxsize", 2000000);
          $up -> set("allowtype", array("gif", "png", "jpg","jpeg"));
          $up -> set("israndname", false);
       
          //使用對象中的upload方法, 就可以上傳文件, 方法需要傳一個上傳表單的名子 pic, 如果成功返回true, 失敗返回false
          if($up -> upload("pic")) {
              echo '<pre>';
              //獲取上傳后文件名子
              var_dump($up->getFileName());
              echo '</pre>';
       
          } else {
              echo '<pre>';
              //獲取上傳失敗以后的錯誤提示
              var_dump($up->getErrorMsg());
              echo '</pre>';
          }
      ?>
      熱門關鍵詞: PHP 文件上傳類 fileupload.class
      欄目列表
      推薦內(nèi)容
      熱點內(nèi)容
      展開