Ogugua Belonwu
Ogugua Belonwu

Reputation: 2141

How can I get the mime type in PHP

I am writing a script and I need to correctly (I think some mime types can be different from their extensions) get the mime types of files (the files can be of any type).

Web hosting company in use does not have mime_content_type() and is still (don't know which year they will be fixing it) promising to fix the PECL alternative.

Which other way can I go about it (and I don;t have access to shell commands)?

Upvotes: 2

Views: 862

Answers (3)

Krunal Shah
Krunal Shah

Reputation: 2101

$_FILES['file']['type'] comes from the browser that uploads the file so you can't rely on this value at all.

Check out finfo_file for identifying file types based on file content. The extension of the file is also unreliable as the user could upload malicious code with an mp3 extension.

Upvotes: 2

Alix Axel
Alix Axel

Reputation: 154513

I use the following function, which is a wrapper for the 3 most common methods:

function Mime($path, $magic = null)
{
    $path = realpath($path);

    if ($path !== false)
    {
        if (function_exists('finfo_open') === true)
        {
            $finfo = finfo_open(FILEINFO_MIME_TYPE, $magic);

            if (is_resource($finfo) === true)
            {
                $result = finfo_file($finfo, $path);
            }

            finfo_close($finfo);
        }

        else if (function_exists('mime_content_type') === true)
        {
            $result = mime_content_type($path);
        }

        else if (function_exists('exif_imagetype') === true)
        {
            $result = image_type_to_mime_type(exif_imagetype($path));
        }

        return preg_replace('~^(.+);.+$~', '$1', $result);
    }

    return false;
}

Upvotes: 2

Mahdi.Montgomery
Mahdi.Montgomery

Reputation: 2024

You could try finfo_file - it returns the mime type.

http://php.net/manual/en/book.fileinfo.php

Upvotes: 2

Related Questions