表單中file對象,比如說$_FILES['doc'],$path為保存的路徑,$type為限制上傳的類型(他是一個數組,比如說限制上傳doc和docx和格式,那麼這個參數可以填array(“doc”,”.docx”),擴展名前有無”.”不作要求)。
複製程式碼 程式碼如下:
function upload($file,$path,$type) {
$state = array();
$state['error'] = "true";
$alltype = ""; // 所有可以上傳的類型,用"/"連接起來
$path = trim($path);
//為$path末尾加上"/"
if(strlen(strrchr($path,'/')) $path .= "/";
}
//為型別加上開頭“.”
//將所有型別合成字串,用"/"連接起來
foreach($type as $key=>$typeone){
$type[$key] = $typeone = trim($typeone);
if(strlen(strchr($typeone,"." )) != strlen($typeone)){
$type[$key] = ".".$typeone;}
$alltype .= $typeone.'/';
}
$alltype = substr($alltype,0,strlen($alltype)-1); //去掉最後的「/」
if(empty($file['name'])){
$state[ 'error'] = "沒有上傳{$alltype}類型檔案!";
$state['errorid'] = 8;
return $state;
} else {
if (!$ file['error']) {
$state['name'] = $file['name'];
$state['type'] = strrchr($state['name'],'. ');
if(in_array($state['type'],$type)){
$time = date("U");
$state['upname'] = $time. rand(1000,9999).$state['type']; //檔命名
if(copy($file['tmp_name'],$path.$state['upname'])){
$state['time'] = date("U"); //上傳的時間
$state['error'] = false;
return $state;
} else {
switch ($file('error')){
case 1: $state['error'] = $state['name']."上傳失敗,檔案大小超出了伺服器的空間大小! ";$state['errorid'] = 1;return $state;
case 2: $state['error'] = $state['name']."上傳失敗,要上傳的檔案大小超出瀏覽器限制! ";$state['errorid'] = 2;return $state;
case 3: $state['error'] = $state['name']."上傳失敗,檔案僅部分上傳! ";$state['errorid'] = 3;return $state;
case 4: $state['error'] = $state['name']."上傳失敗,找不到要上傳的檔案! ";$state['errorid'] = 4;return $state;
case 5: $state['error'] = $state['name']."上傳失敗,伺服器暫存資料夾遺失! ";$state['errorid'] = 5;return $state;
case 6: $state['error'] = $state['name']."上傳失敗,檔案寫入到暫存資料夾出錯! ";$state['errorid'] = 6;return $state;
default: $state['error'] = $state['name']."上傳失敗,位置錯誤! ";$state['errorid'] = 10;return $state;
}
}
} else {
$state['error'] = $state['name']."上傳失敗!不符合要上傳的文件類型! ({$alltype})";
$state['errorid'] = 10;
return $state;
}
}
}
?>