0

我正在开发一个可以上传图片的网页,但代码似乎不起作用。这是另存为 profile2.php 的表单代码:

<form enctype="multipart/form-data" action="upload2.php" method="POST">
Please choose a file: <input name="uploaded" type="file" /><br />
<input type="submit" value="Upload" />
</form>

现在这里是upload2.php 代码:

<?php
  $target = "pictures/";
  $target = $target . basename( $_FILES['uploaded']['name']) ;
  $uploaded = basename( $_FILES['uploaded']['name']) ;

  //This is our size condition
  if ($uploaded_size > 1) {
     echo "Your file is too large.<br>";
     die();
  }

  // This is our limit file type condition
  echo $uploaded_type;
  if (!($uploaded_type=="image/png")&&!($uploaded_type=="image/jpg")) {
      echo "You may only upload png or jpg files.<br>";
      die();
  }

  if(move_uploaded_file($_FILES['uploaded']['tmp_name'], $target)) {
      echo "The file ". $uploaded ." has been uploaded";
  } else {
      echo "Sorry, there was a problem uploading your file.";
  }
?>

所以首先。当我尝试上传 png 图片时,它读取了第二个 if 语句,并说只允许使用 png 和 jpg 文件。我期待它读取第一个 if 语句,因为我的文件肯定大于 1KB。我不知道为什么它忽略了第一个 if 语句并做了第二个 if 语句。任何人都可以帮我解决我的上传代码吗?

4

1 回答 1

2

您盲目地假设上传成功,并盲目地使用未定义的变量并假装它们确实存在。也许这会帮助你:

<?php

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
   if($_FILES['uploaded']['error'] !== UPLOAD_ERR_OK) {
       die("Upload failed with error code " . $_FILES['uploaded']['error']);
   }
   if ($_FILES['uploaded']['size'] > 1) {
      die("File is too large");
      // Are you sure you want "1"? You're basically allowing 1-byte and 0-byte files only
      // since this size is specified in bytes, not kilobytes
   }
   etc...
}

错误代码在这里定义:http ://www.php.net/manual/en/features.file-upload.errors.php

于 2013-07-01T22:09:57.043 回答