這是一個常常在項目中遇到的問題,因此封裝一個,分享給你們。php
一,前期配置php.ini 若是上傳文件超過了php配置那麼$_POST或者$_FILES等都是空數組,這點是一個坑,由於那時候就不能用$_FILES["uploadfile"]["size"]獲取到文件大小了。數組
二,表單實列a.php
服務器
<form action="b.php" method="POST" enctype="multipart/form-data" >
<input type="hidden" name="MAX_FILE_SIZE" value="30">post
<!--若是設置上面這行表示,表單上傳文件大小的限制,這樣$_FILES["upfile"]["size"]爲0,$_FILES["upfile"]["error"]爲2,後面會有介紹"error"-->spa
<input type="file" name="upfile" id="upfile" /><br />
<br />
<input type="submit" />
</form>code
三,php文件b.phporm
<?php圖片
//得到文件擴展名
function get_file_extention( $fileName ){
return end(explode(".",$fileName));
}ip
//得到惟一隨機名字
function get_uniname(){
return md5( uniqid(microtime(true) , true) );
}內存
//上傳處理
function uploadfile($fileInfo,$path="uploads",$allowExt=array("png","jpg","jpeg","gif","zip"),$fileMaxSize=104857600000,$imageTag=true){
if(!$fileInfo){
exit("文件信息錯誤");//多是文件超出了服務器限制
};
if($fileInfo["error"]==0){
//檢查文件大小
if( $fileInfo['size'] > $fileMaxSize){
exit("文件大小超過");
}
//檢查擴展
$ext = get_file_extention($fileInfo['name']);
if( !in_array($ext, $allowExt ) ){
exit("非法文件名");
}
//檢查是不是真正的圖片文件
if(!$imageTag){
if( !getimagesize( $fileInfo['tmp_name'])){
exit("不是真正的圖片文件");
}
}
//檢查文件是不是上傳的文件
if( !is_uploaded_file( $fileInfo['tmp_name'])){
exit("非上傳文件");
}
//檢查上傳目錄是否存在
if(!file_exists($path))
{
mkdir($path,0777,true);
}
$fileName = get_uniname().".".$ext;
$destinationPath = $path."/".$fileName;
//上傳
if(move_uploaded_file($fileInfo['tmp_name'],$destinationPath)){
$result =array("result"=>"圖片上傳成功","code"=>"0000","data"=>$destinationPath);
}else{
$result = array("result"=>"圖片上傳失敗","code"=>"1111","data"=>$destinationPath);
};
}else{
switch($fileInfo['error']){
case 1:
$result=array("result"=>"超過了配置文件上傳文件的大小","code"=>"0001","data"=>"");//UPLOAD_ERR_INI_SIZE
break;
case 2:
$result=array("result"=>"超過了表單設置上傳文件的大小","code"=>"0002","data"=>""); //UPLOAD_ERR_FORM_SIZE
break;
case 3:
$result=array("result"=>"文件部分被上傳","code"=>"0003","data"=>"");//UPLOAD_ERR_PARTIAL
break;
case 4:
$result= array("result"=>"沒有文件被上傳","code"=>"0004","data"=>"");//UPLOAD_ERR_NO_FILE
break;
case 6:
$result= array("result"=>"沒有找到臨時目錄","code"=>"0005","data"=>"");//UPLOAD_ERR_NO_TMP_DIR
break;
case 7:
$result= array("result"=>"文件不可寫","code"=>"0006","data"=>"");//UPLOAD_ERR_CANT_WRITE;
break;
case 8:
$result= array("result"=>"因爲PHP的擴展程序中斷了文件上傳","code"=>"0006","data"=>"");//UPLOAD_ERR_EXTENSION
break;
}
}
return $result;}?>