2016-02-06 31 views
0

我嘗試上傳代碼,但無法找到如何使錯誤僅在其真實時才顯示。因爲現在例如如果文件不是圖像,顯示我所有可能的錯誤。 「文件不是image.Sorry,您的文件太大。只有JPG,JPEG,PNG &允許GIF文件。不過,您的文件沒有上傳。」一切都很好,除了即時嘗試上傳圖像。我想告訴我只有錯誤,並非所有可能的錯誤。所以我希望它現在只顯示只有JPG,JPEG,PNG & GIF文件是允許的。不要它顯示你的文件太大,即使它不太大。我該怎麼做?這裏是全碼:編碼的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"] > 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 {enter code here 
    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."; 
    } 
} 
?> 

P.S林總初學者:)這樣做的時候也有很多潛在的錯誤

+0

鏈接的所有條件與其他檢查錯誤的順序。實際上他們都是獨立的,他們都在你的榜樣中評價爲真。被別的鏈子連接,你的代碼會停在第一個真實的 –

回答

0

一種方法是使用數組。

$errors = array(); 

然後,您只需將錯誤分配給數組,

if (file_exists($target_file)) { 
    $errors[] = "Sorry, file already exists."; 
} 

然後你可以用任何你想要的方式顯示錯誤。

注意 這假定您的錯誤處理從一開始就是正確的。從你的文本來看,你並不期待所有的錯誤。通過if語句檢查if語句來檢查它是否有效,例如如果您上傳的文件具有唯一的名稱,但if (file_exists($target_file))仍然可以作爲true,然後再次查看該代碼。

0

搜索您的文件。一切說回聲,刪除它;並只留下你想要的值。像第13行,它說

echo "File is not an image."; 

刪除該行代碼,你將不會看到「文件不是圖像。」

+0

地獄夥計? :D我想問如何顯示錯誤,只有當它應該顯示..我想看到文件不是圖像,但只有當它的真實,不僅當任何錯誤1是真正的,那麼它顯示所有可能的錯誤。 – Svajukas

+0

確定在您的PHP腳本的開頭創建一個變量。讓我們給它一個名字;我們將其稱爲$錯誤。從<?php $ errors =「」;每次你看到回聲,用$ errors = $ errors替換它。 「文件不是圖像」;或$ errors = $ errors。 「文件不是JPEG」;在腳本結尾處echo $ errors;另外一條逃生路線是使用die();如果有錯誤。它會阻止整個腳本繼續。 –

+0

哦,好的。現在我明白了,謝謝;) – Svajukas

0

錯誤是級聯的。停止錯誤的第一個錯誤即在檢查..

if ($uploadOk AND file_exists($target_file)) { 
    echo "Sorry, file already exists."; 
    $uploadOk = 0; 
} 

你也可能需要改變,其中,如果被返回不正確的錯誤