PHP-檔案上傳封裝類
阿新 • • 發佈:2021-06-18
<?php $file = $_FILES['img']; $obj = new File(); $res = $obj->upload($file,'upload'); if($res){ echo $res; }else{ echo File::$error; } //sleep(30); //Array ( [name] => wjdk.png [type] => image/png [tmp_name] => C:\Windows\php955D.tmp [error] => 0 [size] => 668730 ) class File{ //設定屬性:儲存允許上傳的Mime型別 private static $types = array('image/jpg','imgae/jpeg','image/pjpeg','image/png'); //修改允許上傳的檔案型別 public static function setType($type=array()){ if(!empty($type)){ self::$types = $type; } } public static $error; //記錄檔案上傳過程中出現的錯誤 //上傳方法public static function upload($file,$path,$max = 2000000){ //判斷檔案有效性 if(!isset($file['error']) || count($file) != 5){ self::$error = '錯誤的上傳檔案'; return false; } if(!is_dir($path)){ self::$error = '檔案路徑不存在'; return false; }//判定檔案是否正確上傳 switch ($file['error']){ case 1: case 2: self::$error = '檔案超過伺服器允許大小'; return false; case 3: self::$error = '檔案只有部分被上傳'; return false; case 4: self::$error = '沒有選中要上傳的檔案'; return false; case 6: self::$error = '找不到臨時資料夾'; return false; case 7: self::$error = '檔案寫入失敗'; return false; } //判定檔案型別 if(!in_array($file['type'],self::$types)){ self::$error = '當前上傳的檔案型別不允許'; return false; } //判斷檔案大小 if($file['size'] > $max){ self::$error = '當前上傳的檔案超過允許的大小,當前允許的大小為'.string()($max/1024/1024).'M'; return false; } $filename = self::getRandomName($file['name']); if(move_uploaded_file($file['tmp_name'],$path.'/'.$filename)){ return $filename; }else{ self::$error = '檔案移動失敗'; return false; } } public static function getRandomName($filename,$prefix = 'image'){ $ext = strrchr($filename,'.'); $new_name = $prefix.date('YmdHis'); for($i=0;$i<6;$i++){ $new_name .= chr(mt_rand(65,90)); } return $new_name.$ext; } }