2015-12-30 120 views
2

我有以下代碼上傳圖片在服務器上的文件夾,但問題是,即使我正在上傳正確格式的圖片,它給格式消息 我得到的錯誤是上傳圖片在服務器上的文件夾問題

Sorry, only JPG, JPEG, PNG & GIF files are allowed 

即使圖像是JPG/JPEG/PNG/GIF格式的

的代碼,我現在用的就是

<?php  
if ($_SERVER["REQUEST_METHOD"] == "POST") 
     { 
      $target_dir = "profileimg/"; 
      $target_file = $target_dir . basename($_FILES["fileToUpload"]["name"]); 
      $uploadOk = 1; 
      $imageFileType = pathinfo($target_file,PATHINFO_EXTENSION); 
      // Check if image file is a actual image or fake image 
      if(isset($_POST["submit"])) 
       { 
        if($check !== false) 
         { 
          //echo "File is an image - " . $check["mime"] . "."; 
          $uploadOk = 1; 
         } 
        else 
         { 
          echo "File is not an image."; 
          $uploadOk = 0; 
         } 
       } 

      // Check file size 
      if ($_FILES["fileToUpload"]["size"] > 500000) 
       { 
        echo "Sorry, your file is too large."; 
        $uploadOk = 0; 
       } 

      // Allow certain file formats 
      if($imageFileType != "jpg" || $imageFileType != "png" || $imageFileType != "jpeg" || $imageFileType != "gif") 
       { 
        echo "Sorry, only JPG, JPEG, PNG & GIF files are allowed."; 
        $uploadOk = 0; 
       } 

      // Check if $uploadOk is set to 0 by an error 
      if ($uploadOk == 0) 
       { 
        echo "Sorry, your file was not uploaded."; 
        // if everything is ok, try to upload file 
       } 
      else 
       { 
        $new_filename = $target_dir . uniqid() . '.' . $imageFileType; 
        if (move_uploaded_file($_FILES["fileToUpload"]["tmp_name"], $new_filename)) 
         { 
          echo $new_filename; 

         } 
       } 
     } 
?> 
    <form role="form" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>" method="POST" enctype="multipart/form-data"> 
     <input type="file" class="form-control" id="input01" name="fileToUpload" 
     <button>Submit Form</button> 
    </form> 

誰能PLZ正確次E碼

+0

@Diddle點仍然得到同樣的錯誤 – ne1902

+0

'的print_r($ imageFileType)',看看有什麼在變 –

+0

@Diddle點我沒有得到它價值 – ne1902

回答

2

您的表單標籤需要enctype="multipart/form-data">上傳文件

SO改變

<form role="form" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>" method="POST"> 

TO

<form role="form" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>" method="POST" enctype="multipart/form-data"> 

否則你$_FILES變量是空

,並改變你的驗證,

$allowed = array('gif', 'png', 'jpg', 'jpeg'); 
$filename = $_FILES['fileToUpload']['name']; 
$ext = pathinfo($filename, PATHINFO_EXTENSION); 
if (!in_array($ext, $allowed)) { 
    echo "Sorry, only JPG, JPEG, PNG & GIF files are allowed."; 
    $uploadOk = 0; 
} 
+0

我添加了enctype,但問題仍然相同 – ne1902

+0

檢查更新的答案以檢查文件擴展名 – Saty

1
Sorry, only JPG, JPEG, PNG & GIF files are allowed 

你只檢查JPG和所有,但不是爲JPG或JPG

檢查什麼樣的extantion的有你的文件。 把

strtolower($imageFileType)