getImageMimeType()
Resolves and validates the MIME type of a file, typically an image.
getImageMimeType(string $file[, string|null $format = null ][, array<string|int, mixed> $allowedFormats = [ImageFormat::AVIF => ImageMimeType::AVIF, ImageFormat::JPG => ImageMimeType::JPG, ImageFormat::JPEG => ImageMimeType::JPEG, ImageFormat::PNG => ImageMimeType::PNG, ImageFormat::GIF => ImageMimeType::GIF, ImageFormat::SVG => ImageMimeType::SVG, ImageFormat::WEBP => ImageMimeType::WEBP] ]) : string
This function ensures that the returned MIME type is safe and consistent.
Optionally, it can validate a provided $format
(file extension) against a whitelist
of allowed formats and ensure that it matches the actual MIME type of the file.
Behavior:
- If
$format
is provided and exists in$allowedFormats
:
- Returns the corresponding MIME type if it matches the detected MIME.
- Otherwise, falls back to the actual detected MIME type.
- If
$format
is null or not in$allowedFormats
, the detected MIME is returned.
Parameters
- $file : string
-
Absolute path to the file to check.
- $format : string|null = null
-
Optional desired format (file extension without dot), e.g., "jpg", "png", "webp".
- $allowedFormats : array<string|int, mixed> = [ImageFormat::AVIF => ImageMimeType::AVIF, ImageFormat::JPG => ImageMimeType::JPG, ImageFormat::JPEG => ImageMimeType::JPEG, ImageFormat::PNG => ImageMimeType::PNG, ImageFormat::GIF => ImageMimeType::GIF, ImageFormat::SVG => ImageMimeType::SVG, ImageFormat::WEBP => ImageMimeType::WEBP]
-
Optional whitelist mapping file extensions to MIME types. Defaults to common image formats:
[ 'jpg' => 'image/jpeg', 'jpeg' => 'image/jpeg', 'png' => 'image/png', 'gif' => 'image/gif', 'webp' => 'image/webp', 'svg' => 'image/svg+xml', 'avif' => 'image/avif', ]
Tags
Return values
string —The resolved MIME type of the file.