2015-05-04 37 views
0

我有這個圖像上傳PHP文件。一切似乎除了最大尺寸(300K)的工作,因爲它接受任何大小的圖片...無法識別的最大文件大小PHP

<?php 
if((!empty($_FILES["ex1"])) && ($_FILES['ex1']['error'] == 0)) { 

    $filename = basename($_FILES['ex1']['name']); 

    $ext = substr($filename, strrpos($filename, '.') + 1); 

    if (($ext == "jpg") || ($ext == "jpeg") || ($ext == "png") || ($ext == "gif") && ($_FILES["ex1"]["type"] == "image/jpeg") || ($_FILES["ex1"]["type"] == "image/png") || ($_FILES["ex1"]["type"] == "image/gif") && 
    ($_FILES["ex1"]["size"] < 30000)) { 

     $newname = dirname(__FILE__).'/../temp/'.time(); 

     if (!file_exists($newname)) { 

      if ((move_uploaded_file($_FILES['ex1']['tmp_name'],$newname.'.'.$ext))) { 
      echo "Hecho! Guardada como: ".$newname; 
     } else { 
      echo "Error: Se produjo un problema durante la subida".$newname; 
     } 
     } else { 
     echo "Error: El archivo ".$_FILES["ex1"]["name"]." ya existe"; 
     } 
    } else { 
    echo "Error: Tamaño máximo excedido (300kb) o formato erróneo (jpg, png, gif)"; 
    } 
} else { 
echo "Error: No existe el archivo"; 
} 
?> 
+1

您在支票中缺少一些括號。 –

+0

謝謝。我即將檢查。 – Biomehanika

回答

1

你缺少一些支架。 OR會覆蓋AND,當一個條件匹配時,所有事情都是真實的。周圍的OR塊

廣場支架,像這樣:

if (
    (
     ($ext == "jpg") || ($ext == "jpeg") || ($ext == "png") || ($ext == "gif") 
    ) && (
     ($_FILES["ex1"]["type"] == "image/jpeg") || ($_FILES["ex1"]["type"] == "image/png") || ($_FILES["ex1"]["type"] == "image/gif") 
    ) && (
     ($_FILES["ex1"]["size"] < 30000) 
    ) 
) { 

(縮進爲更好的可讀性)

而且你缺少一個零30000同時檢查文件的大小。

300000相當於大約300KB。

所以,改變

$_FILES["ex1"]["size"] < 30000 

$_FILES["ex1"]["size"] < 300000 
+0

非常感謝。 – Biomehanika

1

&&||更高的優先級,因此a || b && c等於a || (b && c)
您有:

($_FILES["ex1"]["type"] == "image/gif") && ($_FILES["ex1"]["size"] < 30000) 

這意味着,僅比GIF圖像必須小於300KB較小。在你的 「或」 組
用括號括起來:

if (
    (($ext == "jpg") || ($ext == "jpeg") || ($ext == "png") || ($ext == "gif")) && 
    (($_FILES["ex1"]["type"] == "image/jpeg") || ($_FILES["ex1"]["type"] == "image/png") || ($_FILES["ex1"]["type"] == "image/gif")) && 
    ($_FILES["ex1"]["size"] < 30000) 
    ) 
{ 
+0

謝謝。已經解決了。 – Biomehanika

1

兩個傑拉德和Siguza是對他們說些什麼。不過,我想補充一點。

大而複雜的IF條件嚴重影響了代碼的可讀性。你將有興趣在做這樣的事情,而不是:

function handleUpload(){ 
    $maxFileSize = 30000; 
    $allowedExtensions = array('jpg','jpeg','gif'); 

    if($_FILES["ex1"]["size"] > $maxFileSize){ 
     echo "File is too big"; 
     return false; 
    } 

    $ext = substr($filename, strrpos($filename, '.') + 1); 

    if(!in_array($ext, $allowedExtensions)){ 
     echo "Extension not allowed"; 
     return false 
    } 
    // Handle upload 
    return true; 
} 

的目標是: 1 - 返回儘快,這使得代碼更易於閱讀和調試 2 - 不要讓複雜結構,這使得代碼更易於閱讀和調試 3-允許每個塊的註釋,並在上傳失敗時輸出更準確的消息。

如果你遵循這個結構,你會更快,更容易編碼,犯錯誤的機會也會更少。

我希望這會有所幫助。

+0

非常感謝。我會試一試:) – Biomehanika