If you're working in a PHP environment and want to detect MIME types by file extension, using Symfony's Mime component is a great choice. Here’s how to set it up and use it:
Source code viewer
// composer require symfony/mime use Symfony\Component\Mime\MimeTypes; // Function to detect MIME type by file extension function getMimeType($fileName) { $mimeTypes = new MimeTypes(); // Get MIME types based on file extension // - `getMimeTypes()` takes a file extension and returns an array of MIME types for it. // - `[0]` gets the primary MIME type if multiple are possible for a given extension. // - If no match is found, it defaults to 'application/octet-stream'. return $mimeTypes->getMimeTypes(pathinfo($fileName, PATHINFO_EXTENSION))[0] ?? 'application/octet-stream'; } // Example usage $fileName = 'example.png'; $mimeType = getMimeType($fileName); echo $mimeType; // Outputs: 'image/png'Programming Language: PHP