PHP基本的上传文件脚本


PHP basic upload file script

这是我第一次尝试通过PHP上传文件。

这是我的HTML:
<form role="form" action="api/upload.php" id="uploadForm" method="post" enctype="multipart/form-data">
   <input id="fileToUpload" name="fileToUpload" type="file" class="file" />
   <button type="submit" name="submit" id="submit">Upload</button>
</form>

现在这里是PHP脚本参考"api/upload.php":

<?php
$target_dir = "files''";
if(isset($_POST["submit"])) {
$target_file = $target_dir . basename($_FILES["fileToUpload"]["name"]);
$uploadOk = 1;
}
if (file_exists($target_file)) {
echo "Sorry, file already exists.";
$uploadOk = 0;
}
if ($_FILES["fileToUpload"]["size"] > 500000) {
echo "Sorry, your file is too large.";
$uploadOk = 0;
}
if ($uploadOk == 0) {
echo $uploadOk . "Sorry, your file was not uploaded.";
} else {
  if (move_uploaded_file($_FILES["fileToUpload"]["name"], $target_file)) {
   echo "The file ". basename( $_FILES["fileToUpload"]["name"]). " has been uploaded.";
  } else{
     echo "Sorry, there was an error uploading your file.";
  }
} 
?>

这可能是逻辑错误。我不确定。无论如何,我总是得到这样的消息:

对不起,上传文件出错

当我回显$uploadOk时,它仍然是1。我怎样才能找到我的错误?

$_FILES["fileToUpload"]["tmp_name"]代替$_FILES["fileToUpload"]["name"]

应该

move_uploaded_file($_FILES["fileToUpload"]["tmp_name"], $target_file);

指出:-

$_FILES["fileToUpload"]["name"]为上传的文件名。$_FILES["fileToUpload"]["tmp_name"]是保存内容的临时文件

希望对你有帮助。

(编辑1)

我对按钮添加value="submit"属性是错误的。name="submit"属性对于isset($_POST["submit"))检查是足够的