2012-10-28 72 views
-3

目前我已允許上傳.jpg文件。上傳驗證,允許其他擴展?

如何添加jpeg,gif和png?

我當前的代碼如下...

$filename = basename($_FILES['photo']['name']); 
      $ext = substr($filename, strrpos($filename, '.') + 1); 

      //Check if the file is JPEG image and it's size is less than 5Mb 
$allowedExts = array('jpg', 'jpeg', 'gif', 'png'); 
      if ((in_array($ext, $allowedExts)) && ($_FILES["photo"]["type"] == "image/jpeg") && ($_FILES["photo"]["size"] <= 5242880)){ 
       //Determine the path to which we want to save this file 
       $newname = str_replace(' ', '_', trim(strip_tags($_POST['name']))) . _ . $formKey->generateKey() . '_' . time() . '.jpg'; 
+5

當然,你可以有至少一個猜測,並有一個很好的機會,它是正確的。走了,我們會告訴你它是否正確。 – alex

+0

@alex:謝謝。已上傳編輯 – Dave

+0

更新了進一步嘗試的編輯。 – Dave

回答

1

請允許擴展的陣列,以及對證。看看http://php.net/manual/en/function.in-array.php

你會喜歡的東西結束:

$allowedExts = array('jpg', 'jpeg', 'gif'); // Add more here 
if (in_array($ext, $allowedExts)) 
{ 
    // Do something here 
} 

此外,要檢查文件的擴展名,我建議你使用PATHINFO:http://php.net/manual/en/function.pathinfo.php 有些人可以上傳文件以.jpg結尾欺騙你,但這可能是.php文件。

[編輯]更新,因爲我最討厭的小評論:

$allowedExtensions = array("image/jpeg", "image/png", "image/gif", "image/pjpeg", "image/jpg"); 
    $pathInfo = pathinfo($_FILES["photo"]["type"]); 
    if (in_array($pathInfo['extension'], $allowedExtensions)) 
    { 
     // Do stuff 
    } 

Waaaay簡單的這種方式。這甚至可以通過使用pathinfo的第二個參數來簡化,但我假設你需要數組中的其他元素。

+0

感謝 - 更新的問題,仍然無法正常工作。 – Dave

+0

忘記了這個'if((in_array($ ext,$ allowedExts))&&($ _FILES [「photo」] [「type」] ==「image/jpeg」)| |($ _FILES [「photo」] [「type」] ==「image/png」)||($ _FILES [「photo」] [「type」] ==「image/gif」)||($ _FILES [「photo」] [「type」] ==「image/pjpeg」)&&($ _FILES [「photo」] [「size」] <= 5242880))' – Dave

+0

你太過於複雜。我編輯了我的答案。 – Warpten