You need to enable JavaScript to run this app. PHP使用$_FILES上传文件时出现Undefined array key错误如何解决?
优惠活动
大模型
产品
解决方案
定价
更多

PHP使用$_FILES上传文件时出现Undefined array key错误如何解决?

错误原因

  • 表单缺失文件上传必填属性:你的<form>标签仅配置了method="post",未添加文件上传必须的enctype="multipart/form-data"属性,导致浏览器不会将文件内容提交到后端,$_FILES数组中不存在profileimg_regis键,触发未定义数组键的报错。
  • PHP代码参数不匹配:你最后调用move_uploaded_file时使用的键名是fileToUpload,这是教程默认示例参数,而你的表单文件域name属性为profileimg_regis,参数不一致会导致校验通过后也无法完成上传。
  • 缺少上传状态前置校验:代码未判断文件是否成功上传、$_FILES['profileimg_regis']是否存在就直接访问属性,用户未选择文件提交时就会触发空值访问报错。

修复方案

第一步:修改HTML表单

给form标签添加enctype属性,将原有代码

<form action="run/code.php" method="post">

修改为:

<form action="run/code.php" method="post" enctype="multipart/form-data">

第二步:修改PHP代码,补全校验并修正参数

完整修改后的PHP代码如下:

if(isset($_POST["register_btn"])) {
  // 前置校验:判断文件是否成功上传
  if (!isset($_FILES["profileimg_regis"]) || $_FILES["profileimg_regis"]["error"] !== UPLOAD_ERR_OK) {
    echo "请选择有效的头像文件上传";
    exit;
  }

  $target_dir = "img/user/";
  // 自动创建不存在的存储目录,避免移动文件失败
  if (!is_dir($target_dir)) {
    mkdir($target_dir, 0755, true);
  }
  $target_file = $target_dir . basename($_FILES["profileimg_regis"]["name"]);
  $uploadOk = 1;
  $imageFileType = strtolower(pathinfo($target_file,PATHINFO_EXTENSION));

  $check = getimagesize($_FILES["profileimg_regis"]["tmp_name"]);

  if($check !== false) {
    echo "File is an image - " . $check["mime"] . ".";
    $uploadOk = 1;
  } else {
    echo "File is not an image.";
    $uploadOk = 0;
  }

  // 检查文件是否已存在
  if (file_exists($target_file)) {
    echo "Sorry, file already exists.";
    $uploadOk = 0;
  }

  // 检查文件大小
  if ($_FILES["profileimg_regis"]["size"] > 500000) {
    echo "Sorry, your file is too large.";
    $uploadOk = 0;
  }

  // 限制允许的文件格式
  if($imageFileType != "jpg" && $imageFileType != "png" && $imageFileType != "jpeg") {
    echo "Sorry, only JPG, JPEG & PNG files are allowed.";
    $uploadOk = 0;
  }

  // 校验不通过终止上传
  if ($uploadOk == 0) {
    echo "Sorry, your file was not uploaded.";
  } else {
    // 修正上传参数为表单对应name
    if (move_uploaded_file($_FILES["profileimg_regis"]["tmp_name"], $target_file)) {
      echo "The file ". htmlspecialchars( basename( $_FILES["profileimg_regis"]["name"])). " has been uploaded.";
    } else {
      echo "Sorry, there was an error uploading your file.";
    }
  }
}

内容的提问来源于stack exchange,提问作者Deknoinarak

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.12 15:30:04