PHP基本上传文件脚本

时间:2016-08-25 19:22:56

标签: php html upload

这是我第一次尝试通过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脚本参考&#34; api / upload.php&#34;:

<?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.如何找到我的错误?

1 个答案:

答案 0 :(得分:0)

使用$_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"))属性就足够了。