In more detail
A PNG starts 89 50 4E 47, a PDF starts %PDF, a ZIP starts PK. Checking them detects files whose extension lies and underlies upload validation and data carving. Common signatures:
| Format | First bytes (hex) | As text |
|---|---|---|
| PNG | 89 50 4E 47 0D 0A 1A 0A |
.PNG.... |
| JPEG | FF D8 FF |
|
| GIF | 47 49 46 38 |
GIF8 |
25 50 44 46 |
%PDF |
|
| ZIP | 50 4B 03 04 |
PK.. |
| gzip | 1F 8B |
|
| Windows program | 4D 5A |
MZ |
See How File Signatures (Magic Bytes) Work.
Why it matters
The extension is just a label that anyone can change, so deciding what a file is by its name is unsafe. An upload form that trusts .jpg may accept a script; an attachment named report.pdf may be a program. Signatures are still not proof: an attacker can prepend valid bytes to hostile content, and many files are containers (a .docx, .xlsx or .apk all start with PK because they are ZIP archives), so the first bytes narrow the answer without settling it. Formats made of plain text, such as JSON and CSV, have no signature at all.
Example
A real PNG image saved under the wrong name:
$ cp pic.png holiday.jpg
$ file holiday.jpg
holiday.jpg: PNG image data, 4 x 4, 8-bit/color RGB, non-interlaced
$ head -c 8 holiday.jpg | xxd -p
89504e470d0a1a0a
file ignores the name and reads the signature. Do the same with the Binary & Archive Forensics or look a format up in the MIME Type Lookup.