为什么我的上传代码不起作用?

时间:2013-07-01 21:53:38

标签: php upload

我正在开发一个可以上传图片的网页,但代码似乎没有用。以下是保存为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语句。任何人都可以帮我解决上传代码吗?

1 个答案:

答案 0 :(得分: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