PHP Luminova: MIME Detection Utility
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(); // trueCustom MIME Database:
You can use a custom MIME database in two ways:
Set the database before creating the
MIMEobjectMIME::database('/path/to/custom-mime.json'); $mime = new MIME('file.txt');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/jsonGuess from file content
$content = file_get_contents('document.txt');
MIME::guess($content);
// text/plainGuess from stream resource
$fp = fopen('audio.mp3', 'rb');
MIME::guess($fp);
// audio/mpegThe 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/jpegFind file extension by MIME type
Find the file extension that matches a given MIME type.
MIME::findExtension('application/json');
// json
MIME::findExtension('image/jpeg');
// jpgBy default, the method returns the most common extension for the MIME type.
If no matching extension is found, null is returned.
Set
$allExtensionstotrueto 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 jpegLoad 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-streamis returnedThis 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): mixedParameters:
| Parameter | Type | Description |
|---|---|---|
$source | string|resource | The file path MIME string or data string to analyze. |
$mimeDatabase | string|null | Optional 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(): ?stringReturn Value:
string|null - The MIME type, or null if not determined.
getExtension
Get the file extension associated with the MIME type.
public getExtension(): ?stringReturn 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): boolParameters:
| Parameter | Type | Description |
|---|---|---|
$mime | string | The 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(): boolReturn Value:
bool - Returns true if the MIME type indicates text data, false otherwise.
isBinary
Check if the MIME type represents binary data.
public isBinary(): boolReturn Value:
bool - Returns true if the MIME type indicates binary data, false otherwise.
isImage
Check if the MIME type represents an image.
public isImage(): boolReturn 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(): boolReturn Value:
bool - Returns true if the file represents a disk or container image.
isVideo
Check if the MIME type represents video data.
public isVideo(): boolReturn Value:
bool - Returns true if the MIME type indicates video data, false otherwise.
isAudio
Check if the MIME type represents audio data.
public isAudio(): boolReturn 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(): boolReturn 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): boolParameters:
| Parameter | Type | Description |
|---|---|---|
$mime | string | The MIME type string to check. |
$type | int | Maximum length for the type (default: 63). |
$subtype | int | Maximum 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): boolParameters:
| Parameter | Type | Description |
|---|---|---|
$extension | string | The 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): ?stringParameters:
| Parameter | Type | Description |
|---|---|---|
$from | string | File 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|nullParameters:
| Parameter | Type | Description |
|---|---|---|
$mime | string | The MIME type to resolve. |
$allExtensions | bool | Whether 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): voidParameters:
| Parameter | Type | Description |
|---|---|---|
$extension | string | The file extension (without the dot). |
$mime | string | The corresponding MIME type. |
Throws:
- \Luminova\Exceptions\InvalidArgumentException - If the extension or MIME type is invalid.
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): voidParameters:
| Parameter | Type | Description |
|---|---|---|
$file | string | The path to the MIME magic or custom database file. |
Throws:
- \Luminova\Exceptions\RuntimeException - If the file is not readable or cannot be processed.
- \Luminova\Exceptions\InvalidArgumentException - If the file contains invalid extensions or MIME types.
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): boolParameters:
| Parameter | Type | Description |
|---|---|---|
$destination | string | The path to the destination file. |
Return Value:
bool - Returns true if the export was successful, false otherwise.
Throws:
- \Luminova\Exceptions\InvalidArgumentException - If the destination file format is unsupported.
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): ?stringParameters:
| Parameter | Type | Description |
|---|---|---|
$source | string|resource | The file path, resource, MIME string or data string to detect. |
$magicDatabase | string|null | Optional path to a MIME magic database file. |
Return Value:
string|null - Returns the guessed MIME type, or null if it cannot be determined.
Throws:
- \Luminova\Exceptions\InvalidArgumentException - If the source type is invalid.
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'