2016-02-27 71 views
1

我有一個圖片上傳的問題。我正在使用w3schools的表單和腳本。代碼如下。 問題是文件類型的驗證。 getimagesize返回它是一個實際的圖像,但它不能超過文件類型的驗證。 我收到以下錯誤: 文件是圖像 - 圖像/ jpeg。對不起,只允許使用JPG,JPEG,PNG & GIF文件。對不起,你的文件沒有上傳。在php中上傳圖片 - 驗證返回錯誤結果

當我評論驗證發生的if函數時,圖片上傳就好了。

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

我在論壇上看過它,但沒有人有這種類型的錯誤。先謝謝你。

基本形式:

<form action="includes/upload.php" method="post" enctype="multipart/form-data"> 
    Select image to upload: 
    <input type="file" name="fileToUpload" id="fileToUpload"> 
    <input type="submit" value="Upload Image" name="submit"> 
    </form> 

upload.php程序:

<?php 
    $target_dir = "../uploads/"; 
    $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"])) { 
    $check = getimagesize($_FILES["fileToUpload"]["tmp_name"]); 
    if($check !== false) { 
    echo "File is an image - " . $check["mime"] . "."; 
    $uploadOk = 1; 
    } else { 
    echo "File is not an image."; 
    $uploadOk = 0; 
    } 
    } 
    // Check if file already exists 
    if (file_exists($target_file)) { 
    echo "Sorry, file already exists."; 
    $uploadOk = 0; 
    } 
    // Check file size 
    if ($_FILES["fileToUpload"]["size"] > 50000000) { 
    echo "Sorry, your file is too large."; 
    $uploadOk = 0; 
    } 
    // Allow certain file formats 
    // This is where the problem occurs 
    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 { 
    if (move_uploaded_file($_FILES["fileToUpload"]["tmp_name"], $target_file)) { 
    echo "The file ". basename($_FILES["fileToUpload"]["name"]). " has been uploaded."; 
    } else { 
    echo "Sorry, there was an error uploading your file."; 
    } 
    } 
    ?> 
+0

你能說出'$ imageFileType'它適合你條件? 'jpg'?這不等於'png'。 'gif'?這不等於'jpg'。等等。 –

回答

0

使用$_FILES["fileToUpload"]["name"],而不是使用$target_file

$imageFileType = pathinfo($_FILES["fileToUpload"]["name"],PATHINFO_EXTENSION); 
+0

這有點工作,因爲現在一些圖像將上傳,但有些甚至不會說它說文件是一個圖像/ jpeg。 – Sagija