2012-10-27 42 views
1

我是通過文件在php.net link閱讀並沿着以下行來了:

$ _FILES [ 'userfile的'] [「型」]

The mime type of the file, if the browser provided this information. An example 
would be "image/gif". This mime type is however NOT checked on the PHP side 
and therefore don't take its value for granted. 

那麼,如何將一個去核實該文件是一個適當的MIME類型,以阻止用戶上載可能有害的文件到服務器;或以其他方式導致代碼執行服務器端的錯誤(因爲我可能會試圖在一個不是JPEG格式的文件上使用僅用於jpeg的函數)?

在此先感謝

回答

0

您可以使用finfo_file找出PHP認爲什麼類型的文件。不過,我認爲這也不能依賴。我相信它使用啓發式,它不掃描整個文件以確保它完全有效。例如。如果它以<html>之類的開頭,它會說它是text/html,它不會解析整個事情,以確保它是完全正確的。

1
function getMimeType() 
     { 

       $finfo = new finfo(FILEINFO_MIME); 
       $type = $finfo->file($_FILES['field_name']['tmp_name']);//change the field_name 
       $mime = substr($type, 0, strpos($type, ';')); 
       return $mime; 

     } 

     function isValidImage() 
     { 

      $mime = getMimeType(); 
      if(stristr($mime,'image')) 
       return true; 
      else 
       return false; 

     } 
     $res=isValidImage(); 

試試這個,它也會檢查MIME。