上传图片时文件中未定义的索引

时间:2013-09-19 05:47:27

标签: php validation file-upload image-uploading

我正在尝试创建一个用户可以上传图片的表单。我正在使用php验证此文件以查看它是否是图像文件但我收到错误

“未定义的索引文件..”

我无法理解什么是错的..请帮忙

HTML code ..

<html>
<body>

<form action="upload.php" method="post" enctype="multipart/form-data">
<input type="file" name="photo" id="file" /> 
<input type="submit" name="submit" value="Submit" />
</form>
</body>
</html>

PHP代码......

  <?php
  if ((($_FILES["photo"]["type"] == "image/gif")
  || ($_FILES["photo"]["type"] == "image/jpeg")
  || ($_FILES["photo"]["type"] == "image/png"))
  && ($_FILES["photo"]["size"] < 1000000))
  {
  if ($_FILES["photo"]["error"] > 0)
  {
  echo "Return Code: " . $_FILES["photo"]["error"] . " ";
  }
  else
  {
  echo "Upload: " . $_FILES["photo"]["name"] . "";
  echo "Type: " . $_FILES["photo"]["type"] . "";
  echo "Size: " . ($_FILES["photo"]["size"] / 1024) . " Kb";
  echo "Temp file: " . $_FILES["photo"]["tmp_name"] . "";

  if (file_exists("users/" . $_FILES["photo"]["name"]))
  {
  echo $_FILES["photo"]["name"] . " already exists. ";
  }
  else
  {
  move_uploaded_file($_FILES["photo"]["tmp… "users/" . $_FILES["photo"]["name"]);
  echo "Stored in: " . "users/" . $_FILES["photo"]["name"];
  }
  }
  else
  {
  echo "Invalid file";
  }
  ?>

1 个答案:

答案 0 :(得分:1)

您的处理程序有两个问题。

1)您的上一个else条件

之上缺少一个结束括号

2)以下行包含不属于的字符(tmp...中的点):

move_uploaded_file($_FILES["photo"]["tmp… "users/" . $_FILES["photo"]["name"]);

改为:

move_uploaded_file($_FILES["photo"]["tmp_name"], "users/" . $_FILES["photo"]["name"]);

重新格式化的代码,经过测试

<?php
  if ((($_FILES["photo"]["type"] == "image/gif")
  || ($_FILES["photo"]["type"] == "image/jpeg")
  || ($_FILES["photo"]["type"] == "image/png"))
  && ($_FILES["photo"]["size"] < 1000000))
  {
  if ($_FILES["photo"]["error"] > 0)
  {
  echo "Return Code: " . $_FILES["photo"]["error"] . " ";
  }
  else
  {
    echo "Upload: " . $_FILES["photo"]["name"] . "";
    echo "<br>";
    echo "Type: " . $_FILES["photo"]["type"] . "";
    echo "<br>";
    echo "Size: " . ($_FILES["photo"]["size"] / 1024) . " Kb";
    echo "<br>";
    echo "Temp file: " . $_FILES["photo"]["tmp_name"] . "";
    echo "<br>";

  if (file_exists("users/" . $_FILES["photo"]["name"]))
  {
  echo $_FILES["photo"]["name"] . " already exists. ";
  }
  else
  {

// error line for you to compare the error
// move_uploaded_file($_FILES["photo"]["tmp… "users/" . $_FILES["photo"]["name"]);

move_uploaded_file($_FILES["photo"]["tmp_name"], "users/" . $_FILES["photo"]["name"]);

  echo "Stored in: " . "users/" . $_FILES["photo"]["name"];
  }
  }
  } // this was the missing closing brace
  else
  {
  echo "Invalid file";
  }

?>

已添加奖金:我在成功上传后添加了一些echo "<br>";来分隔字段。

这将是这样的:

上传:image_test.jpg
输入:image / jpeg
大小:26.16015625 Kb
临时文件:/ tmp / phpifKd7I
存储在:users / image_test.jpg

而不是一行。