The signatures — magic bytes — that sit in the first few bytes of a file. Use them when identifying file types and implementing validation.
What magic bytes are
Most file formats begin with a fixed byte sequence, known as the magic bytes or file signature. Operating systems and applications read it to decide what kind of file they are looking at. An extension can be changed in a second; the magic bytes are part of the binary itself, which is what makes them a dependable basis for validation.
The file command on Linux and PHP's finfo class both determine the MIME type this way.
Diagram: leading bytes (magic bytes) of common formats
The extension is just part of the filename and an attacker can change it at will: rename shell.php to shell.jpg and an extension check passes. Magic bytes look at the actual start of the data, so renaming does not fool them. They are still weak against polyglot files that fake the first few bytes, so cross-check the extension, the MIME type and the magic bytes together.
How many bytes do I need to identify PNG and JPEG?
PNG needs eight bytes (89 50 4E 47 0D 0A 1A 0A) and JPEG only the first three (FF D8 FF). In practice reading about twelve bytes covers all the common formats at once, including ZIP (50 4B 03 04) and PDF (25 50 44 46). There is no need to load the whole file into memory.
Office documents and APKs are detected as ZIP.
That detection is correct. docx, xlsx, pptx, APK, JAR and EPUB are all ZIP containers and all start with 50 4B 03 04. Telling them apart means opening the archive and looking inside — [Content_Types].xml for docx, AndroidManifest.xml for an APK. You cannot allow docx and reject APK on magic bytes alone.