27 October 2024

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
  1. // composer require symfony/mime
  2.  
  3. use Symfony\Component\Mime\MimeTypes;
  4.  
  5. // Function to detect MIME type by file extension
  6. function getMimeType($fileName) {
  7. $mimeTypes = new MimeTypes();
  8.  
  9. // Get MIME types based on file extension
  10. // - `getMimeTypes()` takes a file extension and returns an array of MIME types for it.
  11. // - `[0]` gets the primary MIME type if multiple are possible for a given extension.
  12. // - If no match is found, it defaults to 'application/octet-stream'.
  13. return $mimeTypes->getMimeTypes(pathinfo($fileName, PATHINFO_EXTENSION))[0] ?? 'application/octet-stream';
  14. }
  15.  
  16. // Example usage
  17. $fileName = 'example.png';
  18. $mimeType = getMimeType($fileName);
  19. echo $mimeType; // Outputs: 'image/png'
Programming Language: PHP