dflydev/apache-mime-types
Parse and query Apache mime.types mappings in PHP. Includes bundled Apache mime.types plus JSON representation. Use parser to read mime.types files, or repositories (PHP, JSON, flat) to look up MIME type by extension and extensions by type.
Installation:
composer require dflydev/apache-mime-types
Add to composer.json if not using autoloading:
"autoload": {
"psr-4": {
"App\\": "app/",
"Dflydev\\ApacheMimeTypes\\": "vendor/dflydev/apache-mime-types/src/"
}
}
Run composer dump-autoload.
First Use Case: Quickly determine a file's MIME type or extensions for a given type:
use Dflydev\ApacheMimeTypes\PhpRepository;
$repository = new PhpRepository();
$type = $repository->findType('php'); // Returns 'text/x-php'
$extensions = $repository->findExtensions('text/html'); // Returns ['html', 'htm']
PhpRepository: Pre-loaded with Apache's mime.types (no parsing needed).JsonRepository: Useful if you need a custom JSON-backed MIME map.Parser: Only needed if you must parse a custom mime.types file.File Uploads: Validate file types before processing:
$repository = new PhpRepository();
$allowedTypes = ['image/jpeg', 'image/png'];
$fileExt = strtolower(pathinfo($request->file('avatar')->getClientOriginalName(), PATHINFO_EXTENSION));
$actualType = $repository->findType($fileExt);
if (!in_array($actualType, $allowedTypes)) {
throw new \InvalidArgumentException("Invalid file type.");
}
Dynamic Content Negotiation:
Serve assets based on Accept headers:
$repository = new PhpRepository();
$preferredType = $request->header('Accept');
$extensions = $repository->findExtensions($preferredType);
// Return the first available extension (e.g., for fallback logic)
$extension = $extensions[0] ?? 'default';
Custom MIME Maps:
Extend JsonRepository for project-specific mappings:
$customJson = json_encode([
'application/vnd.myapp+json' => ['myapp', 'mya']
]);
$repository = new JsonRepository($customJson);
Laravel Filesystem:
Combine with Storage facade for MIME-aware file handling:
use Illuminate\Support\Facades\Storage;
$path = $request->file('file')->store('uploads');
$mime = new PhpRepository();
$type = $mime->findType(pathinfo($path, PATHINFO_EXTENSION));
Storage::disk('s3')->put($path, Storage::get($path), ['mime_type' => $type]);
Validation Rules: Create reusable validation logic:
use Dflydev\ApacheMimeTypes\PhpRepository;
$mimeRepo = new PhpRepository();
$validator = Validator::make($request->all(), [
'file' => ['required', 'mimes:' . implode(',', $mimeRepo->findExtensions('image/jpeg'))]
]);
Service Providers: Bind the repository as a singleton for dependency injection:
$this->app->singleton(PhpRepository::class, function ($app) {
return new PhpRepository();
});
Case Sensitivity: Extensions are case-sensitive in the repository. Normalize inputs:
$extension = strtolower($request->file('file')->getClientOriginalExtension());
Missing Types: Not all extensions/types are covered. Handle fallbacks:
$type = $repository->findType('unknown_ext') ?: 'application/octet-stream';
Parser Overhead:
Avoid using Parser in production unless necessary—it’s slower than PhpRepository or JsonRepository.
JSON Repository Pitfalls:
JsonRepository.Verify Data: Dump the raw repository data to debug:
$repository = new PhpRepository();
dd($repository->getAllTypesAndExtensions());
Check for Typos:
Use findType() or findExtensions() to validate keys:
if (empty($repository->findType('php'))) {
// Likely a typo or missing entry.
}
Custom Parsing:
Extend Parser to handle non-standard mime.types formats:
class CustomParser extends Parser {
protected function parseLine($line) { /* Override logic */ }
}
Hybrid Repository: Combine multiple repositories (e.g., Apache + custom JSON):
class HybridRepository implements RepositoryInterface {
public function findType($extension) {
$apacheRepo = new PhpRepository();
$customRepo = new JsonRepository($customJson);
return $apacheRepo->findType($extension) ?: $customRepo->findType($extension);
}
}
Caching:
Cache repository results for performance (e.g., in Laravel’s app service provider):
$this->app->singleton(PhpRepository::class, function () {
return new PhpRepository(); // Already cached by Composer autoloader.
});
config/ or .env settings. All behavior is code-driven.PhpRepository uses bundled Apache data. To override, use JsonRepository with your own JSON.How can I help you explore Laravel packages today?