通过字节识别文件
http://blog.sina.com.cn/s/blog_62b832910100vmbq.html
通过相关文件格式,获取文件实际类型
YII的代码
class FileTools{
public static function getFileType($file,&$fileType,&$mime){
$bin = substr($file,0,2);
$strInfo = @unpack("C2chars", $bin);
$typeCode = intval($strInfo['chars1'].$strInfo['chars2']);
$fileType = '';
switch ($typeCode)
{
case 7790:
$fileType = 'exe';
return false;
break;
case 7784:
$fileType = 'midi';
return false;
break;
case 8297:
$fileType = 'rar';
return false;
break;
case 255216:
$fileType = 'jpg';
$mime = 'image/jpeg';
return true;
break;
case 7173:
$fileType = 'gif';
$mime = 'image/gif';
return true;
break;
case 6677:
$fileType = 'bmp';
$mime = 'image/bmp';
return true;
break;
case 13780:
$fileType = 'png';
$mime = 'image/png';
return true;
break;
default:
return false;
break;
}
return false;
}
public static function getMimeType($file,$magicFile=null,$checkExtension=true)
{
if(function_exists('finfo_open'))
{
$options=defined('FILEINFO_MIME_TYPE') ? FILEINFO_MIME_TYPE : FILEINFO_MIME;
$info=$magicFile===null ? finfo_open($options) : finfo_open($options,$magicFile);
if($info && ($result=finfo_file($info,$file))!==false)
return $result;
}
if(function_exists('mime_content_type') && ($result=mime_content_type($file))!==false)
return $result;
return $checkExtension ? self::getMimeTypeByExtension($file) : null;
}
/**
* Determines the MIME type based on the extension name of the specified file.
* This method will use a local map between extension name and MIME type.
* @param string $file the file name.
* @param string $magicFile the path of the file that contains all available MIME type information.
* If this is not set, the default 'system.utils.mimeTypes' file will be used.
* This parameter has been available since version 1.1.3.
* @return string the MIME type. Null is returned if the MIME type cannot be determined.
*/
public static function getMimeTypeByExtension($file,$magicFile=null)
{
static $extensions;
if($extensions===null)
$extensions=$magicFile===null ? require('mimeTypes.php') : $magicFile;
if(($ext=pathinfo($file, PATHINFO_EXTENSION))!=='')
{
$ext=strtolower($ext);
if(isset($extensions[$ext]))
return $extensions[$ext];
}
return null;
}
}