本文主題,處理檔案上傳時遇到的各種問題
思想:利用超全域性變數$_FILES所帶的['error']狀態碼確定問題
關於本文的一些關鍵字的定義,一定要注意了!!!
- $_FILES['userfile']['error']
userfiel:上傳檔案時input表單name
error:這個是$_FILES自帶的。不用管;下面的程式會給你說明這是個什麼東西
- move_uploaded_file():
此函式僅用於通過 HTTP POST 上傳的檔案。
如果目標檔案已經存在,將會被覆蓋。
$code = $_FILES['userfile']['error'];
if( $code > 0) { //判斷檔案是否成功上傳到伺服器,0表示上傳成功
echo 'Error: '.$code;
switch ( $code ) {
case UPLOAD_ERR_OK:
//0:沒有錯誤,上傳成功的檔案。
$response = 'There is no error, the file uploaded with success.';
break;
case UPLOAD_ERR_INI_SIZE:
//1:上傳檔案在php.ini中超過upload_max_filesize指令
$response = 'The uploaded file exceeds the upload_max_filesize directive in php.ini.';
break;
case UPLOAD_ERR_FORM_SIZE:
//2:上傳的檔案超過了在HTML表單中指定的max_file_size指令。
$response = 'The uploaded file exceeds the MAX_FILE_SIZE directive that was specified in the HTML form.';
break;
case UPLOAD_ERR_PARTIAL:
//3:上傳的檔案只是部分上傳。
$response = 'The uploaded file was only partially uploaded.';
break;
case UPLOAD_ERR_NO_FILE:
//4:沒有上傳檔案。
$response = 'No file was uploaded.';
break;
case UPLOAD_ERR_NO_TMP_DIR:
//6:缺少一個臨時資料夾中。在PHP 4.3.10和PHP 5.0.3中引入。
$response = 'Missing a temporary folder. Introduced in PHP 4.3.10 and PHP 5.0.3.';
break;
case UPLOAD_ERR_CANT_WRITE:
//7:未能將檔案寫入磁碟。
$response = 'Failed to write file to disk. Introduced in PHP 5.1.0.';
break;
case UPLOAD_ERR_EXTENSION:
//8:PHP擴充套件停止了檔案上傳。PHP沒有提供一種方法來確定是哪個擴充套件導致了檔案上載停止
$response = 'A PHP extension stopped the file upload. PHP does not provide a way to ascertain which extension caused the file upload to stop;';
break;
default:
//未知的錯誤
$response = 'Unknown error';
break;
}
echo $response;
exit; //如果$_FILES['userfile']['error']大於0都是有錯誤,輸出錯誤資訊並退出程式
}else{
echo "success".$code;
$file = $_FILES['userfile'];
var_dump($file);
die;
}
- 另外附上我的一個上傳檔案函式;自我BB一下:簡直是好用的不要不要的。
/*圖片上傳,可改動檔名加密演算法*/
public function uploadFile($file, $path, $allow_type){
$file = $_FILES[$file];
if($file['error'] == 0){
$name = $file['name'];
/*得到上傳檔案的型別,並且都轉化成小寫*/
$file_type = strtolower(substr($name,strrpos($name,'.')+1));
if(!in_array($file_type, $allow_type)){
return "請上傳允許的格式檔案";
}
/*上傳檔案的存放路徑*/
$upload_path = $path.date('Y-m-d').'/';
if( !file_exists($upload_path) ){
mkdir($upload_path,0, true);
}
$sql_url = $upload_path.md5($name.time().rand(4,100) ).'.'.$file_type;
if( move_uploaded_file($file['tmp_name'], $sql_url) ){
/*將狀態碼返回即可,解偶。將需要進行的操作放外面*/
return json_encode(['code'=>$file['error'],'data'=>$sql_url],JSON_UNESCAPED_UNICODE|JSON_PRETTY_PRINT );
}else{
return json_encode(['code'=>$file['error'],'data'=>"上傳失敗,未知錯誤!"],JSON_UNESCAPED_UNICODE|JSON_PRETTY_PRINT );
}
}else{
return json_encode(['code'=>$file['error'],'data'=>"上傳失敗,錯誤程式碼:"],JSON_UNESCAPED_UNICODE|JSON_PRETTY_PRINT );
}
}