Getting an Image's MIME Type

So far we have been handcrafting the header() function call in each of the image scripts, but many people find MIME types hard to remember and/or clumsy to use. If you fit into this category, you should be using the image_type_to_mime_type() function, as it takes a constant as its only parameter and returns the MIME type string. For example, passing in IMAGETYPE_GIF will return image/gif, passing in IMAGETYPE_JPEG will return image/jpeg, and passing in IMAGETYPE_PNG will return image/png.

If you think these constants sound as hard to remember as the MIME types, you're probably right. However, a while back we looked at the getimagesize() function, and I mentioned that the third element in the array returned by that function is the type of file it is. These two functions both use the same constant, which means you can use getimagesize() and pass the third element into image_type_to_mime_type() to have it get the appropriate MIME type for your image—no memorization of constants required.

    $info = getimagesize("button.png");
    print image_type_to_mime_type($info[2]);

Get PHP in a Nutshell now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.