2012-12-17 20 views
5

我有一個網站上的用戶可以上傳文件到一個子目錄。我正在過濾上傳檢查潛在的惡意代碼。我對事物的安全性不熟悉,所以這看起來像是保證上傳到服務器的最佳做法?如果不是,或者我錯過了任何東西,你能指出我朝着正確的方向嗎?這是一個上傳文件的好過濾器嗎?

//arrays with acceptable file extensions/types -- default validations set to false 
$acceptable_ext = array('jpg', 'JPG', 'jpeg', 'JPEG', 'gif', 'GIF', 'png', 'PNG'); 
$acceptable_type = array('image/jpeg', 'image/gif', 'image/png'); 
$validated_ext = 0; 
$validated_type = 0; 

//validate file extension and type 
if($_FILES && $_FILES['file']['name']) { 

    $file_info = pathinfo($_FILES['file']['name']); 

    //validate extension 
    for ($x=0; $x < count($acceptable_ext); $x++) { 
     if($file_info['extension'] == $acceptable_ext[$x]) { 
      $validated_ext = 1; 
     } 
    } 
    //validate type 
    for ($x=0; $x < count($acceptable_type); $x++) { 
     if($file_info['type'] == $acceptable_type[$x]) { 
      $validated_type = 1; 
     } 
    } 
} 

if($validated_ext && $validated_type) { 
    //upload file to the server blah blah 
} 
+0

看起來不錯,但爲什麼2 for循環?你不能在第一個循環中運行這兩項檢查嗎? – NSjonas

+0

數組有兩種不同的長度 – Hat

+1

@flapjacks:'if(in_array($ file_info ['type'],$ acceptable_type))'......只是說......你不需要任何一個循環。 :) – cHao

回答

1

您可以查看一些安全配置here

檢查MIME類型,ini配置,.htaccess等將爲您提供額外的安全性或額外的驗證,每個鏈接。

相關問題