使用PHP的图像上传失败-move_uploaded_file


Image upload failing using PHP - move_uploaded_file

我一直在搜索堆栈溢出和其他教程,了解如何使用php上传文件。下面的脚本可以工作,直到它到达条件为move_uploaded_file($file_temp,$file_destination)的if语句,此时它会返回"file not uploaded"。

包含chmod函数的if语句是我试图将上传文件夹上的文件权限更改为0777(我很确定每个人都可以读写),因为这是许多相关堆栈溢出答案的建议。不过,我不认为问题出在文件权限上。

所以基本上我不知道这是怎么回事。感谢帮助:)

<form action="upload.php" method="post" enctype="multipart/form-data">
  Your Photo: <input type="file" name="image" />
  <input type="submit" name="submit" value="Submit" />
</form>
<?php
 print_r($_FILES);
 // file properties
 $file_name = $_FILES['image']['name'];
 $file_tmp_name = $_FILES['image']['tmp_name'];
 $file_size = $_FILES['image']['size'];
 $file_error = $_FILES['image']['error'];
 // get the extension of the file
 $file_ext = explode('.', $file_name);
 $file_ext = strtolower(end($file_ext));
 var_dump(file_exists('uploads'));
 // this is false
 if(chmod('uploads', 0777) ){
   echo " booooh";
  }
  else{
    echo "naaah";
   }
 $file_name_new = uniqid('', true) . '.' . $file_ext;
 echo "<br>";
 echo $file_destination = '/uploads/' . $file_name;        
 // this is false too
 if(move_uploaded_file($file_temp, $file_destination)) {
   echo "<br>$file_destination<br>";
   echo "hello world<br>";
 }
 else {
   echo "<br>file not uploaded<br>";
 }
 ?>

您编写:

move_uploaded_file( $file_temp, $file_destination );

脚本中未定义$file_temp。原始文件路径为$file_tmp_name

move_uploaded_file( $file_tmp_name, $file_destination );

还要注意,您永远不会使用$file_name_new

附加注意:目标路径必须是绝对文件路径:/uploads/目录必须位于目录树的顶层,而不是文档根目录下。