在php中上传文件时出错

时间:2014-02-27 21:43:55

标签: php

使用Dreamweaver CS6时,我在上传文件时遇到问题。

错误是“无效文件”

这是我的代码:

<?php
    $allowedExts = array("gif", "jpeg", "jpg", "png");
    $temp = explode(".", $_FILES["file"]["name"]);
    $extension = end($temp);
    if ((($_FILES["file"]["type"] == "image/gif")
       || ($_FILES["file"]["type"] == "image/jpeg")
       || ($_FILES["file"]["type"] == "image/jpg")
       || ($_FILES["file"]["type"] == "image/pjpeg")
       || ($_FILES["file"]["type"] == "image/x-png")
       || ($_FILES["file"]["type"] == "image/png"))
       && ($_FILES["file"]["size"] < 20000)
       && in_array($extension, $allowedExts))
       {
         if ($_FILES["file"]["error"] > 0)
         {
           echo "Error: " . $_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 "Stored in: " . $_FILES["file"]["tmp_name"];
         }
       }
       else
       {
         echo "Invalid file";
       }
?>

1 个答案:

答案 0 :(得分:0)

尝试这样的事情:

if ($_FILES["file"]["error"]== 0) {

   $upload_dir = dirname(__FILE__) . "/photos/";

   if (file_exists($upload_dir)) {
      if (is_writable($upload_dir)) {
          $target = $upload_dir; 
          $newName=$_SESSION['theUsername'];
          $target = $target . basename($newName);
          $moved = move_uploaded_file($_FILES['file']['tmp_name'], "$target");
      } else {
          echo 'Upload directory is not writable<br>';
      }
   } else {
      echo 'Upload directory does not exist.<br>';
   }
}