Home >Backend Development >PHP Tutorial >Implementation code for intelligent file type detection using PHP_PHP tutorial
Use file suffix and MIME type detection
Usually when we want to strictly limit the file type, we can simply use $_FILES['myFile']['type'] to get the MIME type of the file and then detect it. Whether it is a legal type.
Alternatively we can take the last few characters of the file name to get the file suffix. Unfortunately, these methods are not sufficient and the extension of the file can be easily changed to bypass this restriction. Furthermore, MIME type information is sent by the browser, and most, if not all, browsers give MIME type information based on the file extension! Therefore, MIME types, like extensions, can be easily spoofed.
Using the "Magic Bytes"
The best way to determine the file type is by examining the first few bytes of the file - known as the "Magic Bytes". Magic bytes are essentially signatures of varying lengths between 2 and 40 bytes in the file header, or at the end of the file. There are hundreds of file types, and quite a few of them have several file signatures associated with them. Here you can see a list of file signatures.
The lazy way is to use the fileinfo extension, which is enabled by default in PHP 5.3.0 (according to the official MANUAL). If it is not enabled, you can enable it yourself
For example, under Windows: