Oihana PHP

API Documentation

Table of Contents

Namespaces

oihana

Functions

getImageMimeType()  : string
Resolves and validates the MIME type of a file, typically an image.

Functions

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:

  1. 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.
  1. 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
throws
InvalidArgumentException

If the file does not exist or is not readable.

throws
FileException

If the file cannot be validated.

example
$mime = getImageMimeType('/path/to/image.png'); // returns 'image/png'
$mime = getImageMimeType('/path/to/image.jpg', 'jpg'); // returns 'image/jpeg'
author

Marc Alcaraz (ekameleon)

since
1.0.0
Return values
string

The resolved MIME type of the file.


        
On this page

Search results