Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP- Get file type by URL

Tags:

file

php

I want to get the file type (eg. image/gif) by URL using PHP.I had tried

<?php
$image_path="http://fc04.deviantart.net/fs71/f/2010/227/4/6/PNG_Test_by_Destron23.png";
exif_imagetype($image_path);
?>

The above code gave me a blank page and the following code returned "3":

<?php
$image_path="http://fc04.deviantart.net/fs71/f/2010/227/4/6/PNG_Test_by_Destron23.png";
echo exif_imagetype($image_path);
?>

Where am I going wrong? Solved: using Fileinfo to fetch content type

like image 354
Ashish Srivastava Avatar asked Sep 18 '14 17:09

Ashish Srivastava


3 Answers

the best way for my understanding

if (!function_exists('getUrlMimeType')) {
    function getUrlMimeType($url)
    {
        $buffer = file_get_contents($url);
        $finfo = new finfo(FILEINFO_MIME_TYPE);
        return $finfo->buffer($buffer);
    }
}

is to create function depend on finfo class

like image 165
Jehad Ahmad Jaghoub Avatar answered Oct 20 '22 18:10

Jehad Ahmad Jaghoub


Here is a PHP function I came up with:

/**
 * @param $image_path
 * @return bool|mixed
 */
function get_image_mime_type($image_path)
{
    $mimes  = array(
        IMAGETYPE_GIF => "image/gif",
        IMAGETYPE_JPEG => "image/jpg",
        IMAGETYPE_PNG => "image/png",
        IMAGETYPE_SWF => "image/swf",
        IMAGETYPE_PSD => "image/psd",
        IMAGETYPE_BMP => "image/bmp",
        IMAGETYPE_TIFF_II => "image/tiff",
        IMAGETYPE_TIFF_MM => "image/tiff",
        IMAGETYPE_JPC => "image/jpc",
        IMAGETYPE_JP2 => "image/jp2",
        IMAGETYPE_JPX => "image/jpx",
        IMAGETYPE_JB2 => "image/jb2",
        IMAGETYPE_SWC => "image/swc",
        IMAGETYPE_IFF => "image/iff",
        IMAGETYPE_WBMP => "image/wbmp",
        IMAGETYPE_XBM => "image/xbm",
        IMAGETYPE_ICO => "image/ico");

    if (($image_type = exif_imagetype($image_path))
        && (array_key_exists($image_type ,$mimes)))
    {
        return $mimes[$image_type];
    }
    else
    {
        return FALSE;
    }
}
like image 30
pgee70 Avatar answered Oct 20 '22 18:10

pgee70


<?php
 $image_path="http://fc04.deviantart.net/fs71/f/2010/227/4/6/PNG_Test_by_Destron23.png";
 echo exif_imagetype($image_path);
?>

It returned 3 because png response type as maciej said.

Try this to get like this image/png:

echo mime_content_type($image_path);

Try this:

$finfo = finfo_open(FILEINFO_MIME_TYPE); // return mime type ala mimetype extension   
echo finfo_file($finfo, $image_path) . "\n";
finfo_close($finfo);
like image 8
Avis Avatar answered Oct 20 '22 18:10

Avis