7

我从这个页面复制了代码:http: //www.w3schools.com/php/php_file_upload.asp

问题是我在上传文件时没有收到错误,而是显示哪个应该是正确的:

上传:images.jpeg 类型:image/jpeg 大小:5.8603515625 kB 临时文件:/tmp/phpZ67YXk 存储在:upload/images.jpeg

但没有文件保存在服务器上。

我不知道出了什么问题,但我在考虑权限,仍然有一个名为 upload 的文件夹具有 777 权限。

这些 php 文件托管在在线 Web 主机上,因此我不在本地运行它。

HTML 格式

<form action="upload_file.php" method="post"
enctype="multipart/form-data">
<label for="file">Filename:</label>
<input type="file" name="file" id="file"><br>
<input type="submit" name="submit" value="Submit">
</form>

</body>
</html>

上传文件.php

<?php
$allowedExts = array("jpg", "jpeg", "gif", "png");
$extension = end(explode(".", $_FILES["file"]["name"]));
if ((($_FILES["file"]["type"] == "image/gif")
|| ($_FILES["file"]["type"] == "image/jpeg")
|| ($_FILES["file"]["type"] == "image/png")
|| ($_FILES["file"]["type"] == "image/pjpeg"))
&& ($_FILES["file"]["size"] < 20000)
&& in_array($extension, $allowedExts))
  {
  if ($_FILES["file"]["error"] > 0)
    {
    echo "Return Code: " . $_FILES["file"]["error"] . "<br>";
    }
  else
    {
    echo "Upload: " . $_FILES["file"]["name"] . "<br>";
    echo "Type: " . $_FILES["file"]["type"] . "<br>";
    echo "Size: " . ($_FILES["file"]["size"] / 1024) . " kB<br>";
    echo "Temp file: " . $_FILES["file"]["tmp_name"] . "<br>";

    if (file_exists("upload/" . $_FILES["file"]["name"]))
      {
      echo $_FILES["file"]["name"] . " already exists. ";
      }
    else
      {
      move_uploaded_file($_FILES["file"]["tmp_name"],
      "upload/" . $_FILES["file"]["name"]);
      echo "Stored in: " . "upload/" . $_FILES["file"]["name"];
      }
    }
  }
else
  {
  echo "Invalid file";
  }
?>
4

2 回答 2

8

我想问题出在您的目标相对路径(相对于您当前的工作目录 = .php 文件的路径),尝试将其设为绝对路径,如下所示:

move_uploaded_file(
  $_FILES["file"]["tmp_name"],
  $_SERVER['DOCUMENT_ROOT'] . 'upload/' . $_FILES["file"]["name"]
);
于 2013-01-22T01:02:13.600 回答
1

这可以帮助您:

chmod 777 foldername

php代码:

<?php
if(isset($_FILES['image'])){
  $errors= array();
  $file_name = $_FILES['image']['name'];
  $file_size =$_FILES['image']['size'];
  $file_tmp =$_FILES['image']['tmp_name'];
  $file_type=$_FILES['image']['type'];
  $file_ext=strtolower(end(explode('.',$_FILES['image']['name'])));
  $expensions= array("jpeg","jpg","png", "mp3",
                     "acc", "wav", "3gpp", "mp4", "3gp", "m4a", "amr", "avi",
                    "flv", "gif");

  if(in_array($file_ext,$expensions)=== false){
     $errors[]="extension not allowed, please choose a JPEG or PNG file.";
  }

  if($file_size > 2097152666655){
     $errors[]='File size must be excately 2 MB';
  }

  if(empty($errors)==true){
     move_uploaded_file($file_tmp,"/var/www/upload/users/".$file_name);
     echo "Success";
  }else{
     print_r($errors);
  }
}
?>

html:

<html>
<body>

  <form action="" method="POST" enctype="multipart/form-data">
     <input type="file" name="image" />
     <input type="submit"/>
  </form>

</body>
</html>
于 2017-04-05T18:26:13.250 回答