Php code used to read the file header and determine the file type

Source: Internet
Author: User
The following describes how to use php to read the file header and determine the file type. it supports image, rar, exe, and other suffixes, if you need a file, you can refer to the php code below to read the file header to determine the file type, and support suffixes such as images, rar, and exe.
Case:
The code is as follows:
// You can use absolute paths such as d:/upload/11.jpg for the image path.
$ File = fopen ($ filename, "rb ");
$ Bin = fread ($ file, 2); // read-only 2 bytes
Fclose ($ file );
$ StrInfo = @ unpack ("C2chars", $ bin );
$ TypeCode = intval ($ strInfo ['chars1']. $ strInfo ['chars2']);
$ FileType = '';
Switch ($ typeCode ){
Case 7790: $ fileType = 'exe '; break;
Case 7784: $ fileType = 'midi '; break;
Case 8297: $ fileType = 'rar '; break;
Case 255216: $ fileType = 'jpg '; break;
Case 7173: $ fileType = 'GIF'; break;
Case 6677: $ fileType = 'bmp '; break;
Case 13780: $ fileType = 'PNG '; break;
Default: echo 'unknown ';
}
Echo 'this is a'. $ fileType. 'File: '. $ typeCode;

Case:
The code is as follows:
?>
// In linux, php also has a function to determine the file type.
Echo mime_content_type('11.gif '). "\ n ";
Echo mime_content_type ('22. php ');
?>

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.