表單中file對象,比如說$_FILES['doc'],$path為儲存的路徑,$type為限制上傳的類型(他是一個數組,比如說限制上傳doc和docx和格式,那這個參數可以填array(“doc”,”.docx”),而且副檔名前有無”.”不作要求)。
複製代碼 代碼如下:<?php
function upload($file,$path,$type){
$state = array();
$state['error'] = "true";
$alltype = ""; // 所有可以上傳的類型,用"/"串連起來
$path = trim($path);
//為$path末尾加上"/"
if(strlen(strrchr($path,‘/‘)) <= 1){
$path .= "/";
}
//為類型加上開頭“.”
//將所有類型合成字串,用"/"串連起來<span id="more-78"></span>
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;
}
}
}
?>
傳回值為一數組
$key value
error 錯誤詳情
errorid 錯誤id(出現錯誤才有值)
type 副檔名(副檔名前帶“.”)
upname 上傳的檔案名稱
time 上傳的時間(從 Unix 紀元(1970-01-01 00:00)開始至今的秒數)
錯誤類型
errorid error
false //上傳成功
1 上傳失敗,檔案大小超出了伺服器的空間大小!
2 上傳失敗,要上傳的檔案大小超出瀏覽器限制!
3 上傳失敗,檔案僅部分被上傳!
4 上傳失敗,沒有找到要上傳的檔案!
5 上傳失敗,伺服器臨時檔案夾丟失!
6 上傳失敗,檔案寫入到臨時檔案夾出錯!
8 沒有上傳該類型檔案! //表單中file對象為空白
10 上傳失敗,位置錯誤!