PHP Luminova: MIME Detection Utility
Detect MIME types and map file extensions to content types.
Luminova’s MIME Detection Utility detects content types from files, streams, or raw content. Its extension database supports lookups, runtime registration, and importing or exporting MIME mappings.
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-streamNo 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 first matching extension in the current database for the MIME type.
If no matching extension is found, null is returned.
Set
$allExtensionstotrueto retrieve all matching extensions instead of only the first 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
The MIME utility 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
Save the mappings in /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
- Full namespace:
Luminova\Utility\Mime - This class is final.
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
__construct
Constructor to initialize MIME type detection.
public function __construct(mixed $source, ?string $mimeDatabase = null)Parameters:
| Parameter | Type | Description |
|---|---|---|
$source | mixed | File path, MIME type, raw data, or stream resource to analyze. |
$mimeDatabase | string\|null | Path to a database accepted by Mime::database() (default: null). Passing a path updates the shared MIME database configuration before inspecting the source. |
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:
Configure a shared database with
Mime::database(), or pass its path as the second constructor argument.
getType
Get the MIME type of the source.
public function getType(): ?stringReturn:
string|null - The MIME type, or null if not determined.
getExtension
Get the file extension associated with the MIME type.
public function getExtension(): ?stringReturn:
string|null - The file extension (without the dot), or null if not determined.
is
Check if the MIME type matches the given type.
public function is(string $mime): boolParameters:
| Parameter | Type | Description |
|---|---|---|
$mime | string | The MIME type to compare against. |
Return:
bool - Returns true if the MIME types match, false otherwise.
isText
Check if the MIME type represents text data.
public function isText(): boolReturn:
bool - Returns true if the MIME type indicates text data, false otherwise.
isBinary
Check if the MIME type represents binary data.
public function isBinary(): boolReturn:
bool - Returns true if the MIME type indicates binary data, false otherwise.
isImage
Check if the MIME type represents an image.
public function isImage(): boolReturn:
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 function isDiskImage(): boolReturn:
bool - Returns true if the file represents a disk or container image.
isVideo
Check if the MIME type represents video data.
public function isVideo(): boolReturn:
bool - Returns true if the MIME type indicates video data, false otherwise.
isAudio
Check if the MIME type represents audio data.
public function isAudio(): boolReturn:
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 function isArchive(): boolReturn:
bool - Return true if the file is an archive or package.
isMimeType
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 function isMimeType(string $mime, int $type = 63, int $subtype = 127): boolParameters:
| Parameter | Type | Description |
|---|---|---|
$mime | string | The MIME type string to check. |
$type | int | Maximum number of characters after the first character in the type (default: 63). |
$subtype | int | Maximum number of characters after the first character in the subtype (default: 127). |
Return:
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 static function isExtension(string $extension): boolParameters:
| Parameter | Type | Description |
|---|---|---|
$extension | string | The file extension to check (without dot). |
Return:
bool - Return true if valid, false otherwise.
getDatabase
Get a list of all registered MIME database files.
public static function getDatabase(): arrayReturn:
array<int,string> - Paths to the loaded MIME databases.
getTypes
Get all registered MIME types.
public static function getTypes(): arrayReturn:
array<string,string> - MIME types keyed by file extension.
findType
Find the MIME type for a given file extension.
public static function findType(string $from): ?stringParameters:
| Parameter | Type | Description |
|---|---|---|
$from | string | File extension, filename, or file path. |
Return:
string|null - Returns the corresponding MIME type, or null if not found.
findExtension
Find file extension(s) for a given MIME type.
public static function 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 matching extensions or only the first database match (default: false). |
Return:
array<int,string>|string|null - With $allExtensions = true, a list of matches or an empty list. Otherwise, the first match or null. MIME parameters such as charset are removed before the lookup.
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 function register(string $extension, string $mime): voidParameters:
| Parameter | Type | Description |
|---|---|---|
$extension | string | The file extension (without the dot). |
$mime | string | The corresponding MIME type. |
Return:
void - This method does not return a value.
Throws:
- Luminova\Exceptions\InvalidArgumentException - If the extension or MIME type is invalid.
Examples:
// 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 function database(string $file): voidParameters:
| Parameter | Type | Description |
|---|---|---|
$file | string | The path to the MIME magic or custom database file. |
Return:
void - This method does not return a value.
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.
Examples:
// 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 mappings replace earlier mappings for the same extension.
export
Export the current MIME type database to a file.
public static function export(string $destination): boolParameters:
| Parameter | Type | Description |
|---|---|---|
$destination | string | The path to the destination file. |
Return:
bool - Returns true if the export was successful, false otherwise.
Throws:
- Luminova\Exceptions\InvalidArgumentException - If the destination file format is unsupported.
Examples:
// 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 function guess(mixed $source, ?string $magicDatabase = null): ?stringParameters:
| Parameter | Type | Description |
|---|---|---|
$source | mixed | The file path, resource, mime string, or data string to detect. |
$magicDatabase | string\|null | Optional path to a MIME magic database file (default: null). |
Return:
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'