1. 程式人生 > >php實現常用文件上傳類

php實現常用文件上傳類

ring item exe bre tex class 允許 excel aud

  1 <?php
  2 /**
  3  * 上傳文件類
  4  * @param _path : 服務器文件存放路徑
  5  * @param _allowType : 允許上傳的文件類型和所對應的MIME
  6  * @param _file : 上傳的文件信息
  7  */
  8 class Upload{
  9 
 10     private $_path;
 11     private $_allowType;
 12     private $_file;
 13     /**
 14      * 構造函數
 15      * @param string : 服務器上存放上傳文件的路徑
16 */ 17 function __construct( $path = ‘‘ ) 18 { 19 $this->_path = $path; 20 $this->_allowType = array( 21 // images 22 ‘bmp‘ => ‘image/x-ms-bmp‘, 23 ‘jpg‘ => ‘image/jpeg‘, 24 ‘jpeg‘ => ‘image/jpeg‘, 25
‘gif‘ => ‘image/gif‘, 26 ‘png‘ => ‘image/png‘, 27 ‘tif‘ => ‘image/tiff‘, 28 ‘tiff‘ => ‘image/tiff‘, 29 ‘tga‘ => ‘image/x-targa‘, 30 ‘psd‘ => ‘image/vnd.adobe.photoshop‘, 31 //
文本 32 ‘txt‘ => ‘text/plain‘, 33 ‘php‘ => ‘text/x-php‘, 34 ‘html‘ => ‘text/html‘, 35 ‘htm‘ => ‘text/html‘, 36 ‘js‘ => ‘text/javascript‘, 37 ‘css‘ => ‘text/css‘, 38 ‘rtf‘ => ‘text/rtf‘, 39 ‘rtfd‘ => ‘text/rtfd‘, 40 ‘py‘ => ‘text/x-python‘, 41 ‘java‘ => ‘text/x-java-source‘, 42 ‘rb‘ => ‘text/x-ruby‘, 43 ‘sh‘ => ‘text/x-shellscript‘, 44 ‘pl‘ => ‘text/x-perl‘, 45 ‘sql‘ => ‘text/x-sql‘, 46 //應用 47 ‘exe‘ => ‘application/octet-stream‘, 48 ‘doc‘ => ‘application/vnd.ms-word‘, 49 ‘docx‘ => ‘application/vnd.ms-word‘, 50 ‘xls‘ => ‘application/vnd.ms-excel‘, 51 ‘ppt‘ => ‘application/vnd.ms-powerpoint‘, 52 ‘pps‘ => ‘application/vnd.ms-powerpoint‘, 53 ‘pdf‘ => ‘application/pdf‘, 54 ‘xml‘ => ‘application/xml‘, 55 //音頻 56 ‘mp3‘ => ‘audio/mpeg‘, 57 ‘mid‘ => ‘audio/midi‘, 58 ‘ogg‘ => ‘audio/ogg‘, 59 ‘mp4a‘ => ‘audio/mp4‘, 60 ‘wav‘ => ‘audio/wav‘, 61 ‘wma‘ => ‘audio/x-ms-wma‘, 62 //視頻 63 ‘avi‘ => ‘video/x-msvideo‘, 64 ‘dv‘ => ‘video/x-dv‘, 65 ‘mp4‘ => ‘video/mp4‘, 66 ‘mpeg‘ => ‘video/mpeg‘, 67 ‘mpg‘ => ‘video/mpeg‘, 68 ‘mov‘ => ‘video/quicktime‘, 69 ‘wm‘ => ‘video/x-ms-wmv‘, 70 ‘flv‘ => ‘video/x-flv‘, 71 ‘mkv‘ => ‘video/x-matroska‘ 72 ); 73 } 74 /** 75 * 上傳函數 76 * @param string : 表單元素的name 值 77 * @return [type] 78 */ 79 public function upload( $txtName = ‘‘ ) 80 { 81 $this->_file = $_FILES[$txtName]; 82 if( $this->_file[‘error‘] == 0){ 83 $fileType = end( explode(‘.‘, $this->_file[‘name‘] )); 84 $allowType = array(); 85 foreach( $this->_allowType as $item=>$value ){ 86 $allowType[] = $item; 87 } 88 if( !in_array($fileType, $allowType)){ 89 die(‘上傳的文件格式不正確!‘); 90 }else{ 91 if(move_uploaded_file($this->file[‘tmp_name‘], ($this->path).$this->file[‘name‘])) 92 { 93 echo "<script>alert(‘上傳成功!‘)</script>"; 94 } 95 else 96 { 97 echo "<script>alert(‘上傳失敗!‘);</script>"; 98 } 99 } 100 101 }else{ 102 //沒有正確上傳 103 switch ($this->file[‘error‘]){ 104 case 1: 105 die(‘文件大小超過系統限制。‘); 106 break; 107 case 2: 108 die(‘文件大小超過預定義限制。‘); 109 break; 110 case 3: 111 die(‘文件為完全上傳。‘); 112 break; 113 case 4: 114 die(‘未上傳任何文件。‘); 115 break; 116 default: 117 die(‘上傳出錯‘); 118 break; 119 } 120 } 121 } 122 //end upload 123 }

php實現常用文件上傳類