PHP- Get file type by URL

后端 未结 7 1257
太阳男子
太阳男子 2020-12-31 16:54

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



        
相关标签:
7条回答
  • 2020-12-31 17:33

    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

    0 讨论(0)
  • 2020-12-31 17:44

    In the first example, you're getting a blank page because you're not doing anything with the return value from the function call. In the second example, you're getting a valid response. See the manual page for exif_imagetype() for a list of what the values mean.

    0 讨论(0)
  • 2020-12-31 17:44

    3 is image type response for PNG image. See: http://php.net/manual/en/function.exif-imagetype.php

    0 讨论(0)
  • 2020-12-31 17:50

    You are not going wrong anywhere. exif_imagetype returns the value of one of the image type constants: http://php.net/manual/en/image.constants.php

    If you would like to convert this to an extension string, you could use a switch statement:

    $typeString = null;
    $typeInt = exif_imagetype($image_path);
    switch($typeInt) {
      case IMG_GIF:
        $typeString = 'image/gif';
        break;
      case IMG_JPG:
        $typeString = 'image/jpg';
        break;
      case IMG_JPEG:
        $typeString = 'image/jpeg';
        break;
      case IMG_PNG:
        $typeString = 'image/png';
        break;
      case IMG_WBMP:
        $typeString = 'image/wbmp';
        break;
      case IMG_XPM:
        $typeString = 'image/xpm';
        break;
      default: 
        $typeString = 'unknown';
    }
    

    You may want to change the order to most to least frequently expected for better performance.

    0 讨论(0)
  • 2020-12-31 17:50

    exif_imagetype returns the image type. The response, 3, indicates it is IMAGETYPE_PNG, the correct response.

    0 讨论(0)
  • 2020-12-31 17:55
    <?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);
    
    0 讨论(0)
提交回复
热议问题