Skip to content

Instantly share code, notes, and snippets.

@vyspiansky
Last active February 21, 2025 13:40
Show Gist options
  • Save vyspiansky/0d7d4acd00343b435b9d0a3880b8b032 to your computer and use it in GitHub Desktop.
Save vyspiansky/0d7d4acd00343b435b9d0a3880b8b032 to your computer and use it in GitHub Desktop.
PHP: retrieve a file extension by its contents

Using Symfony's MimeTypes

use Symfony\Component\Mime\MimeTypes;

function getFileExtension(string $fileContent): ?string
{
    $mimeType = (new \finfo(FILEINFO_MIME_TYPE))->buffer($fileContent);

    $mimeTypes = new MimeTypes();

    $extensions = $mimeTypes->getExtensions($mimeType);

    return $extensions[0] ?? null;
}

Using a plain/pure PHP

function getImageExtension(string $fileContent): ?string
{
    $mimeType = (new \finfo(FILEINFO_MIME_TYPE))->buffer($fileContent);

    // a custom mapping
    return match ($mimeType) {
        'image/gif' => 'gif',
        'image/png' => 'png',
        'image/jpeg' => 'jpg',
        default => null,
    };
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment