• 技术文章 >后端开发 >php教程

    php不通过扩展名准确判断文件类型的方法

    墨辰丷墨辰丷2018-05-23 17:18:31原创537
    这篇文章主要介绍了php不通过扩展名准确判断文件类型的方法,涉及php中finfo_file方法与二进制流针对文件类型的相关操作技巧,需要的朋友可以参考下

    本文实例讲述了php实现不通过扩展名准确判断文件类型的方法。分享给大家供大家参考,具体如下:

    第一种方法

    通过php的finfo_file()

    $handle=finfo_open(FILEINFO_MIME_TYPE);//This function opens a magic database and returns its resource. 
    $fileInfo=finfo_file($handle,'./test.txt');// Return information about a file
    finfo_close($handle);
    print_r($fileInfo);
    echo '==========="\n"';

    另外

    finfo_buffer: Return information about a string buffer
    finfo_close: Close fileinfo resource
    mime_content_type:Detect MIME Content-type for a file (deprecated)

    第二种方法

    通过二进制流获取文件内容

    $fp=fopen('test.txt','r')///实际是image/png
    $bin = fread($fp, 2); //只读2字节
    fclose($fp);
    $str_info = @unpack(“C2chars”, $bin);//Unpack data from binary string
    $type_code = intval($str_info['chars1'].$str_info['chars2']);// Get the integer value of a variable
    $file_type = ”;
    switch ($type_code) {
    case 7790:
    $file_type = 'exe';
    break;
    case 7784:
    $file_type = 'midi';
    break;
    case 8075:
    $file_type = 'zip';
    break;
    case 8297:
    $file_type = 'rar';
    break;
    case 255216:
    $file_type = 'jpg';
    break;
    case 7173:
    $file_type = 'gif';
    break;
    case 6677:
    $file_type = 'bmp';
    break;
    case 13780:
    $file_type = 'png';
    break;
    default:
    $file_type = 'unknown';
    break;
    }

    以上就是本文的全部内容,希望对大家的学习有所帮助。


    相关推荐:

    PHP程序中的文件锁、互斥锁、读写锁使用技巧解析_php技巧

    PHP编程中尝试程序并发的几种方式总结_php技巧

    PHP的Laravel框架中使用AdminLTE模板来编写网站后台界面_php技巧

    以上就是php不通过扩展名准确判断文件类型的方法的详细内容,更多请关注php中文网其它相关文章!

    声明:本文原创发布php中文网,转载请注明出处,感谢您的尊重!如有疑问,请联系admin@php.cn处理
    专题推荐:php 扩展名 文件
    上一篇:PHP使用finfo_file()函数实现检测上传图片类型的方法 下一篇:PHP实现递归删除多维数组中的某个值
    大前端线上培训班

    相关文章推荐

    • PHP中怎样完成Cookie的创建、读取和删除?• PHP中怎样完成Session的设置、获取和删除?• 带你分清类中的构造函数与析构函数• PHP中的命名空间定义与使用(实例详解)• PHP中clone关键字和__clone()方法的使用(实例详解)

    全部评论我要评论

  • 取消发布评论发送
  • 1/1

    PHP中文网