♂WhiteWin♂

导航

【辅导】Task11 如何获取文件上传错误信息

    使用$_FILES[‘file’][‘error’]系统变量获取的是文件上传控件当前的错误代码(int型),无法向用户提供更确定的错误信息,以帮助用户了解是什么原因导致的文件上传错误。

    在php手册(php.net)上,对文件上传信息错误代码定义如下(参见 https://www.php.net/manual/zh/features.file-upload.errors.php):

UPLOAD_ERR_OK
其值为 0,没有错误发生,文件上传成功。
UPLOAD_ERR_INI_SIZE
其值为 1,上传的文件超过了 php.ini 中 upload_max_filesize 选项限制的值。
UPLOAD_ERR_FORM_SIZE
其值为 2,上传文件的大小超过了 HTML 表单中 MAX_FILE_SIZE 选项指定的值。
UPLOAD_ERR_PARTIAL
其值为 3,文件只有部分被上传。
UPLOAD_ERR_NO_FILE
其值为 4,没有文件被上传。
UPLOAD_ERR_NO_TMP_DIR
其值为 6,找不到临时文件夹。PHP 5.0.3 引进。
UPLOAD_ERR_CANT_WRITE
其值为 7,文件写入失败。PHP 5.1.0 引进。
UPLOAD_ERR_EXTENSION
Value: 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. Introduced in PHP 5.2.0.

    我们可以定义下面这样的函数,以获取错误信息的描述:

function codeToMessage($code) {
   switch ($code) {
       case UPLOAD_ERR_INI_SIZE:
       $message = "The uploaded file exceeds the upload_max_filesize directive in php.ini";
          break;
       case UPLOAD_ERR_FORM_SIZE:
         $message = "The uploaded file exceeds the MAX_FILE_SIZE directive that was specified in the HTML form";
          break;
       case UPLOAD_ERR_PARTIAL:
          $message = "The uploaded file was only partially uploaded";
          break;
       case UPLOAD_ERR_NO_FILE:
          $message = "No file was uploaded";
          break;
       case UPLOAD_ERR_NO_TMP_DIR:
          $message = "Missing a temporary folder";
          break;
       case UPLOAD_ERR_CANT_WRITE:
          $message = "Failed to write file to disk";
          break;
       case UPLOAD_ERR_EXTENSION:
          $message = "File upload stopped by extension";
          break;
       default:
          $message = "Unknown upload error";
          break;
   }
   return $message;
}

    这样,在处理文件上传时,可以显示错误信息的具体内容:

if ($_FILES['file']['error']){
  $hasErr = true;
  $fileErr = '文件上传错误:'.codeToMessage($_FILES['file']['error']);
}

 

posted on 2022-04-04 10:32  银翼  阅读(53)  评论(0编辑  收藏  举报