PHP: Getting the File Type of an Image

I am working on an image upload plugin that uses JQuery. I am using PHP on the backend. I have found that there are multiple ways to use PHP to get the file extension of an image.


PathInfo is probably the most common way get information about a file.

$path_parts = pathinfo('');
echo $path_parts['dirname']; //output:
echo $path_parts['basename']; //output: pic1.png
echo $path_parts['extension']; //output: png
echo $path_parts['filename']; //output: pic1


Although I have used PHP’s getimagesize to get the dimensions of an image, it can also be used to get other information (to include the file type):

list($width, $height, $type) = getimagesize('pic1.png');
echo $type; //output: png


Recently, I stumbled upon a new way to get the file extension:

$file_name = current(explode('.', 'pic1.png'));
$ext = end(explode('.', 'pic1.png'));
echo $file_name; //output: pic1
echo $ext; //output: png

I’m sure there are other ways to use PHP to get the file type as well.

Be Sociable, Share!

Checkout My New Site - T-shirts For Geeks