[PHP] 上傳圖片檔案,並驗證檔案大小、類型

以前案子都一兩頁,所以沒有特別寫Function,今天因為有很多的頁面有上傳圖檔的關係,所以就寫了一個Function針對驗證及上傳

如果想要上傳圖片檔案,並驗證檔案大小 ,格式等..,可考慮用以下方式進行。

/**
*
* $FILES 非陣列,一次檢查一個檔 並上傳
* $Path 資料夾路徑
* $Size 檔案大小限制 單位b
*
* 回傳 Array
* status 狀態 布林值
* Message 錯誤時提供 錯誤原因
* FileName 成功時提供 文件名稱
* */
function FileUpload($FILES, $Path, $Size, $Type, $NewName = NULL) {
//上傳得錯誤的錯誤訊息
  $uploadErrors = array(
    0 => "There is no error, the file uploaded with success",
    1 => "The uploaded file exceeds the upload_max_filesize directive in php.ini",
    2 => "The uploaded file exceeds the MAX_FILE_SIZE directive that was specified in the HTML form",
    3 => "The uploaded file was only partially uploaded",
    4 => "No file was uploaded",
    6 => "Missing a temporary folder",
    7 => 'Failed to write file to disk.',
    8 => 'A PHP extension stopped the file upload. PHP does not provide a way to ascertain which extension caused the file upload to stop; examining the list of loaded extensions with phpinfo() may help.'
);
 
//是否為空
if (!isset($FILES)) {
    return "No upload found  ";
} else if (isset($FILES["error"]) && $FILES["error"] != 0) { //是否有錯誤 0表示無錯誤
    return $uploadErrors[$FILES["error"]];
} else if (empty($FILES['name'])) { //是否有檔案名字
    return array("Status" => FALSE, "Message" => "File has no name.");
}
//是否為圖檔
if (!@getimagesize($FILES["tmp_name"])) {
    return array("Status" => FALSE, "Message" => "Is not a images");
}
 
//檔案大小 是否超過
if (!isset($FILES["size"]) || $FILES["size"] > $Size) {
    return array("Status" => FALSE, "Message" => "File exceeds the maximum allowed size ".$FILES['size']." / $Size .");
}
 
//檔案大小 是否異常
if ($FILES["size"] <= 0) { return array("Status" => FALSE, "Message" => "File size outside allowed lower bound");
}
 
//取出副檔名並驗證是否非指定的檔案
$imageFileType = pathinfo(basename($FILES["name"]), PATHINFO_EXTENSION);
if (!in_array(strtolower($imageFileType), $Type)) {
    return array("Status" => FALSE, "Message" => "Images Type is Fail");
}
 
//建立新名稱 如果沒有傳值,就用原本的檔名,如有傳值,則用傳進來的檔名
if (empty($NewName)) {
    $newFileName = $FILES["name"];
} else {
    $newFileName = $NewName . '.' . $imageFileType;
}
 
//執行上傳
if (!move_uploaded_file($FILES["tmp_name"], $Path . $newFileName)) {
    return array("Status" => FALSE, "Message" => "Move upload error.");
}
 
//完成
return array("Status" => TRUE, "FileName" => $newFileName);
}

/*********************PHP程式***************************/
 
//準備要上傳的路徑位置
$FilePath = 'upload/';
 
if (!is_dir($FilePath)) { //檢查資料夾是否存在
if (!mkdir($FilePath, 755, true)) //不存在的話就創建資料夾
die("上傳目錄不存在,並且創建失敗");
}
//執行FileUpload 做上傳動作
$FileUploadStatus = FileUpload($_FILES['ImgFile'], $FilePath, 2 * 1024 * 1024, array('jpg', 'jpeg', 'gif', 'png'), $newName);
if ($FileUploadStatus['Status'] != 'Success') {
echo '<script>alert("' . $FileUploadStatus['Message'] . '");</script>'; //以JS輸出錯誤訊息
exit;
}
 
echo '上傳完成,檔名:'.$FileUploadStatus['FileName'];
<form method="POST" enctype="multipart/form-data">
<input name="ImgFile" accept="image/*"  type="file">
</form>

發佈留言

發佈留言必須填寫的電子郵件地址不會公開。 必填欄位標示為 *