通過判斷 限制上傳檔案的格式為 PDF,docx,xlsx,pptx,potx,vsdx,odt,doc,xls,ppt,vsd,pot,wps,dps,et和txt,rtf檔案類型 希望大家多提意見!
- function checkFileType($filename){
- //檔案頭
- $_typecode = array(
- '3780',//PDF
- '8075',//.docx,.xlsx,.pptx,.potx,.vsdx,.odt
- '208207',//.doc,.xls,.ppt,.vsd,.pot,.wps,.dps,.et
- );
- $file = fopen($filename, "rb");
- //contents = stream_get_contents($file);
- //$contents = fread($file, filesize($filename));
- $bin = fread($file, 2); //唯讀2位元組
- fclose($file);
- $strInfo = @unpack("C2chars", $bin);// C為不帶正負號的整數,網上搜到的都是c,為有符號整數,這樣會產生負數判斷不正常
- $typeCode = intval($strInfo['chars1'].$strInfo['chars2']);
- exec("file $filename",$output,$return_var);//用linux系統命令file判斷上傳檔案的類型,主要是判斷txt,rtf檔案類型
- $pattern = '/text,/';//rtf和txt文檔用file檢測都會被檢測為text
- $_count = preg_match($pattern,strrchr($output[0],":"));
- echo $typeCode;
- if(in_array($typeCode,$_typecode) || $_count == 1) {
- return true;
- }else{
- return false;
- }
- }
複製代碼 |