PHP

Detect MIME Type via Magic Bytes

admin by @admin ADMIN
4d ago
May 31, 2026
Public
0 0 up · 0 down Sign in to vote
Use PHP's built-in finfo (libmagic) to detect a file's true MIME type from its bytes — not from the extension, which can be lied about. Critical for validating user uploads.
PHP
Raw
<?php
function detectMime(string $path): string {
    if (!is_file($path)) throw new RuntimeException("$path is not a file");
    $finfo = new finfo(FILEINFO_MIME_TYPE);
    $mime  = $finfo->file($path);
    if ($mime === false) throw new RuntimeException('MIME detection failed');
    return $mime;
}

function isImageUpload(string $path): bool {
    $allowed = ['image/jpeg', 'image/png', 'image/gif', 'image/webp'];
    return in_array(detectMime($path), $allowed, true);
}

// User says "it's a .png" — we verify by looking at the bytes.
if (!isImageUpload($_FILES['avatar']['tmp_name'])) {
    http_response_code(415);
    exit('Only JPEG/PNG/GIF/WebP allowed');
}
Tags

Save your own code snippets

Create a free account and build your private vault. Share publicly whenever you want.