PHP Get Mime Type From File Extension

Overview

Whenever you need to determine the mime-type of a file you should generally look at the file extension. Below is a pretty straight forward function that will return the mime-type of a file based on its file extension. Note! this is not a guaranteed way to determine the mime-type since people can easily fake the file extension. All you need to do is pass the php mime function a filename and it will try figure out what the mime type is.

PHP Get Mime Type From File Extension

Here is the function to retrieve the mime type of a file based on the file extension. See here for a list of mime-types.

<?php

function get_mime_type($file)
{

	// our list of mime types
	$mime_types = array(
		"pdf"=>"application/pdf"
		,"exe"=>"application/octet-stream"
		,"zip"=>"application/zip"
		,"docx"=>"application/msword"
		,"doc"=>"application/msword"
		,"xls"=>"application/vnd.ms-excel"
		,"ppt"=>"application/vnd.ms-powerpoint"
		,"gif"=>"image/gif"
		,"png"=>"image/png"
		,"jpeg"=>"image/jpg"
		,"jpg"=>"image/jpg"
		,"mp3"=>"audio/mpeg"
		,"wav"=>"audio/x-wav"
		,"mpeg"=>"video/mpeg"
		,"mpg"=>"video/mpeg"
		,"mpe"=>"video/mpeg"
		,"mov"=>"video/quicktime"
		,"avi"=>"video/x-msvideo"
		,"3gp"=>"video/3gpp"
		,"css"=>"text/css"
		,"jsc"=>"application/javascript"
		,"js"=>"application/javascript"
		,"php"=>"text/html"
		,"htm"=>"text/html"
		,"html"=>"text/html"
	);

	$extension = strtolower(end(explode('.',$file)));

	return $mime_types[$extension];
}

?>

Usage Examples

Here are a couple of ways to use this function.

<?php

// simple calls to fetch mime type of a file
echo get_mime_type('example.doc'); // displays "application/msword"
echo get_mime_type('picture.jpg'); // displays "image/jpg"
echo get_mime_type('Harry_Potter.mov'); // displays "video/quicktime"

Advanced Example

This example is slightly more advanced. It will set the http header image/jpg and output the image file. It can be used for displaying an image from a php script.

<?php

$mime = get_mime_type('my_image_file.jpg'); // this will return "image/jpg"
header("Content-Type: $mime");
echo file_get_contents('my_image_file.jpg'); // output the image to the browser
?>