Weave 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

Php Mimetyper Laravel Package

adrienrn/php-mimetyper

A lightweight PHP library for MIME type mapping. Look up MIME types by file extension and extensions by MIME type through a simple API, useful for uploads, validation, and content headers without relying on file inspection.

Deep Wiki
Context7

Getting Started

Install with Composer and check the PHP constraint in composer.json before wiring it into an older app:

composer require adrienrn/php-mimetyper

Look first at the README’s API section and the generated data source under src/ (or resources/), because this package is essentially a thin, fast lookup layer over the jshttp/mime-db dataset. The data is bundled, so there is no runtime network call and no external service to configure.

The first practical use case is resolving a detected MIME type to a safe file extension after upload:

use Adrienrn\MimeTyper\MimeTypes;

$mimeTypes = new MimeTypes();

$extensions = $mimeTypes->getExtensions('image/jpeg');
// ['jpeg', 'jpg', 'jpe'] (order depends on the bundled db)

$extension = $extensions[0] ?? 'bin';
$storedName = $uuid . '.' . $extension;

The reverse lookup is just as useful when serving a file:

$mimeTypes = $mimeTypes->getMimeTypes('pdf');
// ['application/pdf']

Use this package as a mapping layer, not as a replacement for actual content inspection. Pair it with finfo or Symfony’s Mime component to detect what a file really is, then use this library to decide what extension or Content-Type to attach.

Implementation Patterns

Upload validation pipeline. Detect the real MIME type server-side, normalize it, then use this package to enumerate acceptable extensions and compare against your allowlist:

$finfo = new finfo(FILEINFO_MIME_TYPE);
$detected = $finfo->file($uploadedFile->getRealPath());

$allowedMime = ['image/jpeg', 'image/png', 'application/pdf'];
if (!in_array($detected, $allowedMime, true)) {
    throw new ValidationException('Unsupported file type');
}

$extensions = $mimeTypes->getExtensions($detected);
$safeExtension = $extensions[0] ?? 'bin';

Storing files with a canonical extension. Do not trust the client filename extension. Store the original name in metadata, but derive the physical filename extension from the detected MIME type. This keeps storage consistent even when users upload .jpeg, .JPG, or extensionless files.

Serving downloads with the correct Content-Type. When streaming a stored file, map its extension back to a MIME type and set the header explicitly:

$mime = $mimeTypes->getMimeTypes($extension)[0] ?? 'application/octet-stream';

return response()->streamDownload($callback, $downloadName, [
    'Content-Type' => $mime,
]);

Laravel integration. Register the mapper as a singleton in a service provider so the bundled data is loaded once per request lifecycle:

$this->app->singleton(MimeTypes::class, fn () => new MimeTypes());

Then inject it into form requests, jobs, or controllers. If the package ships a service provider or facade, prefer that and publish any config only if you actually need to override mappings. In validation rules, resolve the mapper from the container rather than instantiating it per rule.

Symfony integration. Autowire the class as a service. This package complements Symfony\Component\Mime: use Symfony’s component for message composition and detection, and this library when you need extension-to-MIME or MIME-to-extension lookups without pulling in the full MIME message machinery.

Bulk import and migration workflows. If you are normalizing thousands of records, build a small in-memory map once:

$map = [];
foreach ($mimeTypes->getAllMimeTypes() as $mime) {
    $map[$mime] = $mimeTypes->getExtensions($mime);
}

Check the actual method names in the README, but the pattern is to avoid repeated per-row object construction. If your dataset is very large, cache the derived map in Redis or a config file and invalidate it when the package is upgraded.

API content negotiation. When clients send an Accept header or request a download format, use the reverse lookup to pick a valid extension and attach the matching MIME type to the response. Keep a small explicit allowlist on top of the package so you never serve an unexpected format.

Testing. Because the mapping data is bundled and deterministic, tests are straightforward. Assert that known MIME types resolve to expected extensions, and assert fallback behavior for unknown values. Pin the package version in composer.lock if exact mapping order matters in tests.

Gotchas and Tips

  • MIME mappings are not one-to-one. image/jpeg maps to multiple extensions, and a single extension can map to multiple MIME types. Never assume the first element is universally correct; define your own preferred order if the output order is user-visible.
  • Strip MIME parameters before lookup. A value like text/html; charset=UTF-8 will not match a plain text/html key. Normalize with something like explode(';', $mime)[0] and trim/lowercase first.
  • Never trust $_FILES['type']. That value is client-supplied. Use finfo and treat this package as a mapping utility, not a security control. Validate magic bytes or use a dedicated scanner for untrusted uploads.
  • Handle unknown types explicitly. Return application/octet-stream or bin as a fallback; do not let a missing key turn into a null extension or an empty Content-Type.
  • Normalize extensions. Decide whether your code expects jpg or .jpg. Strip leading dots and lowercase before calling the mapper, and be consistent across callers.
  • application/octet-stream is ambiguous. It often maps to bin, but many real files may be reported this way. Do not use it to infer a safe extension without additional inspection.
  • Upgrade data intentionally. The mappings come from jshttp/mime-db; a package update can change available extensions or ordering. If extensions are persisted or used in URLs, add tests around the mappings you depend on.
  • Reuse the instance. Loading the bundled dataset repeatedly is wasteful. Bind it as a singleton in Laravel or register it as a shared service in Symfony, especially in queue workers processing many files.
  • Laravel config caching. If you publish config or register custom mappings, remember php artisan config:cache during deployment; stale caches are a common source of “it works locally” bugs.
  • Overlap with Symfony Mime. Both libraries can answer similar questions. Pick one as the source of truth for mapping and avoid mixing outputs in the same workflow, or you will get inconsistent extension choices.
  • Extension point for custom mappings. Wrap the package in your own FileTypeResolver service so you can inject overrides for proprietary types, change fallback behavior, and swap the implementation later without touching call sites.
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.
tequilarapido/trackit
gregsphotography/site-builder-filament
cabaoctavio/laravel-query-log
gregsphotography/site-builder-components
io-digital/clickatell
snowsoft/laravel-admin
oxygen/auth
relicsoftware/barakah-payment-gateway
tobya/work-with-composer
equipc/laravel-email-validator
equipc/laravel-email-database-log
adedsec/nova-translated-labels
wazza/laravel-db-encryption
hokny/laravel-generator
vonsogt/backup
jengo/queues
jeremykenedy/laravel-observability
coleus/frame
thtg88/journalism
filagora/filagora-ai-forums