PHP中获取文件扩展名的N种方法
第1种方法:
function get_extension($file)
{
substr(strrchr($file, '.'), 1);
}
第2种方法:
function get_extension($file)
{
return substr($file, strrpos($file, '.')+1);
}
第3种方法:
function get_extension($file)
{
return end(explode('.', $file));
}
第4种方法:
function get_extension($file)
{
$info = pathinfo($file);
return $info['extension'];
}
第5种方法:
function get_extension($file)
{
return pathinfo($file, PATHINFO_EXTENSION);
}
以上几种方式粗看了一下,好像都行,特别是1、2种方法,在我不知道
pathinfo
有第二个参数之前也一直在用。但是仔细考虑一下,前四种方法都有各种各样的毛病。要想完全正确获取文件的扩展名,必须要能处理以下三种特殊情况。
没有文件扩展名
路径中包含了字符.,如/home/test.d/test.txt
路径中包含了字符.,但文件没有扩展名。如/home/test.d/test
很明显:1、2不能处理第三种情况,3不能正确处理第一三种情况。4可以正确处理,但是在不存在扩展名时,会发出一个警告。只有第5种方法才是最正确的方法。
第6种方法:
$tempfile = @fopen($img, "rb");
$bin = fread($tempfile, 2); //只读2字节
fclose($tempfile);
$strInfo = @unpack("C2chars", $bin);
$typeCode = intval($strInfo['chars1'] . $strInfo['chars2']);
$fileType = '';
switch ($typeCode){ // 6677:bmp 255216:jpg 7173:gif 13780:png 7790:exe 8297:rar 8075:zip tar:109121 7z:55122 gz 31139
case '255216':
$fileType = 'jpg';
break;
case '7173':
$fileType = 'gif';
break;
case '13780':
$fileType = 'png';
break;
default:
$fileType = 'unknown';
}
直接读文件头,根本不管上传者指定的扩展名,哪怕你不指定扩展名,目前为止还准确着,^_^。比如把 upall.png 改名为 upall.jpg 上传、或改名为 upall.uim,也可以准确读出文件名为 upall.png