0

我的上传脚本似乎甚至没有上传它设计的文件类型。这是脚本:

<?php

$allowedExts = array("jpg", "jpeg", "gif", "png");

$extension = end(explode(".", $_FILES["file"]["name"]));

if ((($_FILES["file"]["type"] == "image/gif")
|| ($_FILES["file"]["type"] == "image/jpeg")
|| ($_FILES["file"]["type"] == "image/png")
|| ($_FILES["file"]["type"] == "image/pjpeg"))
&& ($_FILES["file"]["size"] < 20000)
&& in_array($extension, $allowedExts))
  {
  if ($_FILES["file"]["error"] > 0)
    {
    echo "Return Code: " . $_FILES["file"]["error"] . "<br>";
    }
  else
    {
    echo "Upload: " . $_FILES["file"]["name"] . "<br>";
    echo "Type: " . $_FILES["file"]["type"] . "<br>";
    echo "Size: " . ($_FILES["file"]["size"] / 1024) . " kB<br>";
    echo "Temp file: " . $_FILES["file"]["tmp_name"] . "<br>";

    if (file_exists("upload/" . $_FILES["file"]["name"]))
      {
      echo $_FILES["file"]["name"] . " already exists. ";
      }
    else
      {
      move_uploaded_file($_FILES["file"]["tmp_name"],
      "upload/" . $_FILES["file"]["name"]);
      echo "Stored in: " . "upload/" . $_FILES["file"]["name"];
      }
    }
  }
else
  {
  echo "Invalid file";
  }
?>

无论我更改什么,该脚本似乎总是将文件列为“无效文件”。相反,我希望它上传到与上传者位于同一目录中的某个文件。

4

1 回答 1

1

使用更具描述性的错误。如有必要,更改工作流程。

例如:

$allowedExts = array("jpg", "jpeg", "gif", "png");
$mimes       = array('image/gif','image/jpeg','image/png','image/pjpeg');
$extension = end(explode(".", $_FILES["file"]["name"]));

function check_errors()
{
    if (!in_array($_FILES["file"]["type"], $mimes))
        return "Invalid MIME type: " . $_FILES["file"]["type"];
    if ($_FILES["file"]["size"] >= 20000)
        return "File too long: size=" . $_FILES["file"]["size"];
    if (!in_array($extension, $allowedExts))
        return "Extension not allowed: '".$extension."'";
    if ($_FILES["file"]["error"] > 0)
        return "Return code " . $_FILES["file"]["error"];
    return "OK";
}

if ('OK' == ($reason = check_errors()))
{
    // your code
}
else
{
    echo "ERROR: $reason";
}
于 2013-01-05T17:41:18.273 回答