PHP Get Mime Type From File Extension


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.


function get_mime_type($file)

	// our list of mime types
	$mime_types = array(

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

	return $mime_types[$extension];


Usage Examples

Here are a couple of ways to use this function.


// 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(''); // 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.


$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