PHP reads the file header (2 bytes) to determine the file type

Source: Internet
Author: User
If you see this title, you may say whether the file type is correct. if you directly judge whether the extension does not know the file type, but the extension is easy to forge, This bypasses the judgment. Most files store a special number or character in a specific position (2 bytes at the beginning )/*

If you see this title, you may say whether the file type is correct. if you directly judge whether the extension does not know the file type, but the extension is easy to forge, This bypasses the judgment.
Most files store a special number or character in a specific position (2 bytes at the beginning)

/*** @ Author Mckee * @ link http://www.phpddt.com * // use 'B' to force the use of binary mode $ fp = fopen('qq.jpg ', 'RB '); // read-only binary file. The first two bytes can be used to determine the file type $ bin = fread ($ fp, 2); fclose ($ fp ); // Convert a binary string to a formatted string. here it is converted to a decimal integer $ code = unpack ('c2chars', $ bin); // An array is returned here, let's take a look at $ type_code = intval ($ code ['chars1']. $ code ['chars2']); $ type = ''; switch ($ type_code) {case 255216: $ type = 'jpg '; break; case 7173: $ type = 'gif '; break; case 6677: $ type = 'bmp'; break; case 13780: $ type = 'PNG '; break; default: $ type = 'unknown ';} echo $ type;

The above code is just an introduction and is not accurate. readers can study it on their own. even this can be forged. if it is an image type, many people will use getimagesize ($ file) to judge it.

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.