使用finfo_file()函数检测上传图片的类型

@date:2016-02-24 21:01:00

该函数可以检测文件的MIME类型。因为有时候我们只根据文件后缀来判断是不准确的。

function getMIME($filename){
    $finfo = finfo_open(FILEINFO_MIME_TYPE); 
    return finfo_file($finfo, $filename); 
}

echo getMIME('test.jpg'); //image/jpeg

finfo_file 文档

(PHP >= 5.3.0, PECL fileinfo >= 0.1.0)

finfo_file -- finfo::file — Return information about a file,This function is used to get information about a file.

完整例子:

<html>
	<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
    <head>
        <title>文件上传</title>
    </head>
    <body>
    <form accept="" method="post" enctype="multipart/form-data">
    <input  type="file" name="img[]" /><br />
    <input  type="submit" name="s" /><br />
    </form>
	
<?php

    //上传文件信息
    $img = $_FILES['img'];
    if ($img)
    {
		//文件存放目录,和本php文件同级
		$dir = dirname(__file__);

		$filename = $img['name'][0];
		$tempname = $img['tmp_name'][0];

		$savepath = "$dir\\$filename";
		$state = move_uploaded_file($tempname, $savepath);
		//如果上传成功,预览
		if($state)
		{
			echo "<img src='$filename' alt='$filename' /> ";
		}
		
		$finfo = finfo_open(FILEINFO_MIME_TYPE); 
		//$mime = finfo_file($finfo, dirname(__FILE__)."/".$filename); 
		$mime = finfo_file($finfo, $savepath); 
		echo $mime;

    }
?>
    </body>
</html>

如果是jpg文件,输出image/jpeg。

Build by Loppo 0.6.14