该函数可以检测文件的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。
时间: 2024-10-24 18:46:24