Luminova Framework

PHP Luminova: MIME Detection Utility

Last updated: 2026-01-25 19:21:15

A lightweight PHP MIME utility for detecting content types from files, filenames, streams, or raw data. Supports custom MIME databases, extension lookup, and reliable guessing of MIME types.

The MIME class helps you detect, manage, and work with MIME types in a consistent way.It supports files, filenames, raw content, streams, and custom MIME databases.

This class is designed to be:

  • Easy to understand
  • Safe for production
  • Useful for both beginners and experienced developers

Key Features

  • Guess MIME type from:

    • File path
    • Filename (image.png)
    • Raw string content
    • Stream resource
  • Find MIME type by extension
  • Find extension by MIME type
  • Register custom MIME types
  • Load MIME databases (.json, .txt, .php, magic db)
  • Export MIME database to text
  • Safe handling of application/octet-stream
  • No HTML output, no side effects

Examples

Detect MIME Object

You can detect the MIME type from a file path, filename, extension, or raw content.Internally, this behaves the same as calling the guess() method. With helper methods like isImage() save you from string comparisons and bad guesses.

use Luminova\Utility\MIME;

$mime = new MIME('image.png');

$mime->getType();      // image/png
$mime->getExtension(); // png
$mime->isImage();      // true

Custom MIME Database:

You can use a custom MIME database in two ways:

  1. Set the database before creating the MIME object

    MIME::database('/path/to/custom-mime.json');
    $mime = new MIME('file.txt');
  2. Pass a magic database directly to the constructor

    $mime = new MIME('file.txt', '/path/to/magic.mgc');

This allows MIME to resolve types using your own mappings or a custom magic file.


Guess MIME type

use Luminova\Utility\MIME;

MIME::guess('image.png');
// image/png

MIME::guess('/path/to/file.pdf');
// application/pdf

MIME::guess('{"key":"value"}');
// application/json

Guess from file content

$content = file_get_contents('document.txt');

MIME::guess($content);
// text/plain

Guess from stream resource

$fp = fopen('audio.mp3', 'rb');

MIME::guess($fp);
// audio/mpeg

The stream pointer is preserved.No data is lost.


Find MIME type by extension

MIME::findType('json');
// application/json

// Dots and spaces are trimmed automatically.
MIME::findType('.jpg');
// image/jpeg

Find file extension by MIME type

Find the file extension that matches a given MIME type.

MIME::findExtension('application/json');
// json

MIME::findExtension('image/jpeg');
// jpg

By default, the method returns the most common extension for the MIME type.

If no matching extension is found, null is returned.

Set $allExtensions to true to retrieve all matching extensions instead of only the most common one.


Register custom MIME types

MIME::register('log', 'text/plain');
MIME::register('md', 'text/markdown');

// Register a MIME type manually
MIME::register('custom', 'application/custom-type');

Load from MIME Databases

Extend Custom MIME and Extensions

MIME class is ships with a built-in MIME database that covers common file types.You only need to set custom database when handling custom or vendor-specific.

Custom MIME definitions can be registered during application class, custom class or in a controller (for example, in an onCreate() method).

Load from JSON format

# /writable/custom/mime.json

{
  "json": "application/json",
  "csv": "text/csv",
  "md": "text/markdown"
}

Load a custom MIME database from a JSON file

MIME::database('/writable/custom/mime.json');

Load from Text format

Extensions sharing the same MIME type are grouped.

# /writable/custom/mime.txt

# MIME type                 Extensions
text/plain                  txt text conf log
application/json            json
image/jpeg                  jpg jpeg

Load from a plain text MIME list

MIME::database('/writable/custom/mime.txt');

Load from PHP file

Extensions sharing the same MIME type are grouped.

// /writable/custom/mime.php

return [
    'txt'   => 'text/plain',
    'text'  => 'text/plain',
    'conf'  => 'text/plain',
    'log'   => 'text/plain',
    'json'  => 'application/json',
    'jpg'   => 'image/jpeg',
    'jpeg'  => 'image/jpeg',
]

Load from a PHP file that returns an array

MIME::database('/writable/custom/mime.php');

Magic database

Used internally by finfo, no extension is required.

MIME::database('/writable/custom/mime.mgc');

Export MIME database

Export as JSON or TEXT format. The export destination file extension is used to determine format (e.g, mime.txt exports as TEXT, mime.json exports as JSON format).

MIME::export('mime.txt');

Useful for debugging, sharing, or version control.


Class Definition

  • Class namespace: \Luminova\Utility\MIME
  • This class is a Final class

Note:

When application/octet-stream is returned

This means:

  • Binary content
  • Unknown type
  • Detection was inconclusive

This is not an error. It is the correct and safe fallback.


Methods

constructor

Constructor to initialize MIME type detection.

public __construct(resource|string $source, ?string $mimeDatabase = null): mixed

Parameters:

ParameterTypeDescription
$sourcestring|resourceThe file path MIME string or data string to analyze.
$mimeDatabasestring|nullOptional path to MIME magic or custom database file.

Examples:

use Luminova\Utility\MIME;

// Create a new MIME instance for a file
$mime = new MIME('/path/to/file.jpg');

// Get the MIME type of the file
echo $mime->getType(); // Output: image/jpeg

// Get the file extension
echo $mime->getExtension(); // Output: jpg

// Check if the file is an image
var_dump($mime->isImage()); // Output: bool(true)

Note:

So use a custom MIME database with constructor, you can set database before initializing MIME object.Or pass magic MIME database as the second arguments $mimeDatabase


getType

Get the MIME type of the source.

public getType(): ?string

Return Value:

string|null - The MIME type, or null if not determined.


getExtension

Get the file extension associated with the MIME type.

public getExtension(): ?string

Return Value:

string|null - The file extension (without the dot), or null if not determined.


is

Check if the MIME type matches the given type.

public is(string $mime): bool

Parameters:

ParameterTypeDescription
$mimestringThe MIME type to compare against.

Return Value:

bool - Returns true if the MIME types match, false otherwise.


isText

Check if the MIME type represents text data.

public isText(): bool

Return Value:

bool - Returns true if the MIME type indicates text data, false otherwise.


isBinary

Check if the MIME type represents binary data.

public isBinary(): bool

Return Value:

bool - Returns true if the MIME type indicates binary data, false otherwise.


isImage

Check if the MIME type represents an image.

public isImage(): bool

Return Value:

bool - Returns true if the MIME type indicates an image, false otherwise.

This checks only browser renderable images.


isDiskImage

Determine whether the file is a non-renderable image or disk image.

This method identifies formats that are commonly classified as images or image containers but are not directly viewable (e.g. PSD, ISO, DMG).

public isDiskImage(): bool

Return Value:

bool - Returns true if the file represents a disk or container image.


isVideo

Check if the MIME type represents video data.

public isVideo(): bool

Return Value:

bool - Returns true if the MIME type indicates video data, false otherwise.


isAudio

Check if the MIME type represents audio data.

public isAudio(): bool

Return Value:

bool - Returns true if the MIME type indicates audio data, false otherwise.


isArchive

Determine whether the file is an archive or package.

Includes traditional archives (zip, tar, 7z, rar, etc.) and runtime packages (apk, jar, war, aar).

public isArchive(): bool

Return Value:

bool - Return true if the file is an archive or package.


isMimeTypes

Determine if a string is a valid MIME type.

Checks the format type/subtype, optionally with suffixes like +xml.his does NOT validate parameters (e.g., ; charset=utf-8) strictly RFC-compliant.

public static isMimeType(string $mime, int $type = 63, int $subtype = 127): bool

Parameters:

ParameterTypeDescription
$mimestringThe MIME type string to check.
$typeintMaximum length for the type (default: 63).
$subtypeintMaximum length for the subtype (default 127).

Return Value:

bool - Return true if the string is a valid MIME type format, false otherwise.


isExtension

Determine if a string is a valid file extension.

Supports:

  • Single-part extensions: "zip", "exe"
  • Compound extensions: "tar.gz", "backup.2026"
  • Each segment: 1–10 alphanumeric characters
public isExtension(string $extension): bool

Parameters:

ParameterTypeDescription
$extensionstringThe file extension to check (without dot).

Return Value:

bool - Return true if valid, false otherwise.


getDatabase

Get a list of all registered MIME database files.

public static getDatabase(): string[]

Return Value:

string[] - Returns an array of file paths.


getTypes

Get all registered MIME types.

public static getTypes(): array<string,string>

Return Value:

array<string,string> - Returns an array of MIME types and extension as key.


findType

Find the MIME type for a given file extension.

public static findType(string $from): ?string

Parameters:

ParameterTypeDescription
$fromstringFile extension, filename, or file path.

Return Value:

string|null - Returns the corresponding MIME type, or null if not found.


findExtension

Find file extension(s) for a given MIME type.

public static findExtension(string $mime, bool $allExtensions = false): array|string|null

Parameters:

ParameterTypeDescription
$mimestringThe MIME type to resolve.
$allExtensionsboolWhether to return all or only the first (most common) extension (default: false).

Return Value:

array<int,string>|string|null - Returns the corresponding file extension, or null if not found.


register

Register a new MIME type for a given file extension.

  • Extensions: a–z, 0–9, max 10 chars
  • MIME types: RFC-compliant (type/subtype)
public static register(string $extension, string $mime): void

Parameters:

ParameterTypeDescription
$extensionstringThe file extension (without the dot).
$mimestringThe corresponding MIME type.

Throws:

Example:

// Register a new MIME type for a custom file extension
MIME::register('custom', 'application/custom-type');

database

Load a custom MIME type database from a file.

Supported file formats:

  • .mgc: Binary magic database file (used by PHP finfo).
  • .json: JSON file with MIME type mappings {'ext': 'mime/type', ...}.
  • .txt: Text file with lines in the format 'mime/type ext1 ext2 ext3'. Lines starting with '#' are ignored.
  • .php: PHP file that returns an array of MIME return ['ext' => 'mime/type'].
public static database(string $file): void

Parameters:

ParameterTypeDescription
$filestringThe path to the MIME magic or custom database file.

Throws:

Example:

// Load a custom MIME database
MIME::database('/writable/custom/mime.json');

// Guess MIME types
MIME::guess('mime.txt');

Note:Multiple databases can be loaded by calling MIME::database() multiple times.Later entries merge with earlier ones, without overwriting previously registered extensions.


export

Export the current MIME type database to a file.

public static export(string $destination): bool

Parameters:

ParameterTypeDescription
$destinationstringThe path to the destination file.

Return Value:

bool - Returns true if the export was successful, false otherwise.

Throws:

Example:

// Export the current MIME database to a JSON file
MIME::export('/writable/custom/mime.json');

guess

Guess the MIME type of a given source.

This method detects MIME type from a file path, stream resource, or raw data.

This method attempts MIME detection in a safe and predictable order:

  • If a file path is provided, it detects the MIME type from the file.
  • If a stream resource is provided, it first checks the file uri (if any).
  • Stream fallback, using the first bytes of the stream without altering the stream position.

The stream cursor is always restored to its original position, making thismethod safe to use before or during file reads.

public static guess(string|resource $source, ?string $magicDatabase = null): ?string

Parameters:

ParameterTypeDescription
$sourcestring|resourceThe file path, resource, MIME string or data string to detect.
$magicDatabasestring|nullOptional path to a MIME magic database file.

Return Value:

string|null - Returns the guessed MIME type, or null if it cannot be determined.

Throws:

Examples:

// Guess the MIME from a file with custom magic database
MIME::guess('audio.mp3', '/writable/custom/mime.mgc'); // 'audio/mpeg'

// Guess the MIME from filename
MIME::guess('mime.txt'); // 'text/plain'

// Guess the MIME from content
MIME::guess('{"key":"value"}'); // 'application/json'

// Guess the MIME from file content
$content = file_get_contents('mime.txt');
MIME::guess($content); // 'text/plain'

// Guess the MIME from file
MIME::guess('/path/to/audio.mp3'); // 'audio/mpeg'