Weave Code
Code Weaver
Helps Laravel developers discover, compare, and choose open-source packages. See popularity, security, maintainers, and scores at a glance to make better decisions.
Feedback
Share your thoughts, report bugs, or suggest improvements.
Subject
Message

Mime Type Detection Laravel Package

league/mime-type-detection

Fast, reliable MIME type detection for PHP. Detects from file extensions and binary signatures using shared databases, with a simple API and customizable mappings. Ideal for uploads, validation, and content-type handling in Laravel and other PHP apps.

View on GitHub
Deep Wiki
Context7

Getting Started

Install the package via Composer: composer require league/mime-type-detection. It requires the ext-fileinfo extension — ensure it’s enabled (check via php -i | grep fileinfo). Start with the default detector for file-based detection:

use League\MimeTypeDetection\FinfoMimeTypeDetector;

$detector = new FinfoMimeTypeDetector();
$mimeType = $detector->detectMimeType('/path/to/file.jpg'); // 'image/jpeg'

For Laravel, register it as a singleton in AppServiceProvider or use it directly in services. First use case: validating file uploads in a form request by detecting MIME type from the uploaded file’s content (not just the extension).

Implementation Patterns

  • Laravel integration: Inject the detector into middleware, commands, or domain services. Example validation in a FormRequest:
    protected function withValidator($validator)
    {
        $validator->after(function ($validator) {
            $detector = new FinfoMimeTypeDetector();
            $file = $this->file('document');
            if ($file && !in_array($detector->detectMimeType($file->getPathname()), ['application/pdf', 'application/vnd.openxmlformats-officedocument.wordprocessingml.document'])) {
                $validator->errors()->add('document', 'Invalid file type.');
            }
        });
    }
    
  • Flysystem integration: When using league/flysystem v3+, this package is used internally via MimetypeDetectionExtension. You rarely interact with it directly — Flysystem auto-detects MIME on writes.
  • Buffer-based detection: For uploaded files in memory (e.g., UploadedFile::getSize() > 0), use:
    $detector->detectMimeTypeFromBuffer(file_get_contents($request->file('avatar')->getPathname()));
    
    Or more efficiently, pass a limited buffer size to avoid memory spikes:
    new FinfoMimeTypeDetector(null, 8192); // 8KB sample
    
  • Reverse lookup for filenames: Generate safe extensions when downloading files:
    $extensions = $detector->getExtensionsForMimeType('image/webp'); // ['webp']
    $filename = "download." . ($extensions[0] ?? 'dat');
    
  • Fallback strategies: Combine detectors via ChainMimeTypeDetector to prioritize content-based detection but fall back to extension mapping if finfo fails:
    $detector = new ChainMimeTypeDetector([
        new FinfoMimeTypeDetector(),
        new ExtensionToMimeTypeMap(),
    ]);
    

Gotchas and Tips

  • finfo extension is mandatory: If detectMimeType() returns false, verify extension=fileinfo is in php.ini (commonly missing in minimal Docker images).
  • Inconclusive detections: For ambiguous files (e.g., .txt containing JSON), the detector may return text/plain — configure treatInconclusiveAs in constructor (e.g., 'application/octet-stream') for stricter handling.
  • Small-file pitfalls: Very small files (< 512 bytes) may return false from buffer-based detection. Test first or use full-file detection.
  • PHP 8.4 readiness: Starting v1.16.0, the package avoids implicit ?string returns where possible. Avoid ?string type-hinting in your code relying on its return values until you’re confident on deprecation behavior.
  • Extension overrides: Need custom types (e.g., application/x-myapp) for internal services? Wrap the map:
    $map = new OverridingExtensionToMimeTypeMap(
        new ExtensionToMimeTypeMap(),
        ['myapp' => 'application/x-myapp']
    );
    
  • Composer updates matter: MIME types evolve (e.g., new AVIF, HEIC support). Run composer update league/mime-type-detection periodically — recent changelogs show frequent lookup updates (1.11.0 through 1.16.0).
  • Reverse lookup returns arrays: Always guard array_shift() calls:
    $ext = $detector->getExtensionsForMimeType($mimeType)[0] ?? 'bin';
    
Weaver

How can I help you explore Laravel packages today?

Conversation history is not saved when not logged in.
Prompt
Add packages to context
No packages found.
davejamesmiller/laravel-breadcrumbs
artisanry/parsedown
christhompsontldr/phpsdk
enqueue/dsn
bunny/bunny
enqueue/test
enqueue/null
enqueue/amqp-tools
milesj/emojibase
bower-asset/punycode
bower-asset/inputmask
bower-asset/jquery
bower-asset/yii2-pjax
laravel/nova
spatie/laravel-mailcoach
spatie/laravel-superseeder
laravel/liferaft
nst/json-test-suite
danielmiessler/sec-lists
jackalope/jackalope-transport