萬盛學電腦網

 萬盛學電腦網 >> 網絡編程 >> php編程 >> php獲取上傳文件類型 獲取文件後綴

php獲取上傳文件類型 獲取文件後綴

本教程提供了三款獲取上傳文件與圖片類型的方法,方法也是很簡單的前二種,是先把類型定義好,再用in_array判斷,最後一步是利用了fopen再讀取前二個字節,判斷。  代碼如下 復制代碼

//獲得圖片的格式,包括jpg,png,gif
function get_type($img_name)//獲取圖像文件類型
{
 if (preg_match("/.(jpg|jpeg|gif|png|bmp)$/i", $img_name, $matches)){
  $type = strtolower($matches[1]);
 }else{
  $type = "string";
 }
 return $type;
}

//判斷上傳文件類型
$allowedextensions = array("txt","csv","htm","html","xml",  
    "css教程","doc","xls","rtf","ppt","pdf","swf","flv","avi",  
    "wmv","mov","jpg","jpeg","gif","png");   
    foreach ($_files as $file) {  
    if ($file['tmp_name'] > '') {  
      if (!in_array(end(explode(".",  
            strtolower($file['name']))),  
            $allowedextensions)) {  
       die($file['name'].' is an invalid file type!<br/>'.  
        '<a href="網頁特效:history.go(-1);">'.  
        '&lt;&lt go back</a>');  
      }  
}  
}  

//另類的讀取文件與圖片類型

function checktitle($filename) {
$file     = fopen($filename, "rb");
$bin      = fread($file, 2); //只讀2字節
fclose($file);
$strinfo  = @unpack("c2chars", $bin);
$typecode = intval($strinfo['chars1'].$strinfo['chars2']);
$filetype = "";
switch ($typecode)
{
 case 7790:
 $filetype = 'exe';
 break;
 case 7784:
 $filetype = 'midi';
 break;
 case 8297:
 $filetype = 'rar';
 break;
 case 255216:
 $filetype = 'jpg';
 break;
 case 7173:
 $filetype = 'gif';
 break;
 case 6677:
 $filetype = 'bmp';
 break;
 case 13780:
 $filetype = 'png';
 break;
 default:
 $filetype = 'unknown'.$typecode;
}
//fix
if ($strinfo['chars1']=='-1' && $strinfo['chars2']=='-40' ) {
return 'jpg';
}
if ($strinfo['chars1']=='-119' && $strinfo['chars2']=='80' ) {
return 'png';
}
return $filetype;
}

 

?>

copyright © 萬盛學電腦網 all rights reserved