1. 程式人生 > >php獲取圖片真實後綴的兩種方法

php獲取圖片真實後綴的兩種方法

php獲取圖片真實後綴的兩種方法

一、getimagesize(支持base64):
  1. 代碼:
    <?php
    /*
    @desc:獲取圖片真實後綴
    @param   name    文件名
    @return  suffix  文件後綴
    */   
    function getimgsuffix($name) {
    $info = getimagesize($name);
    $suffix = false;
    if($mime = $info[‘mime‘]){
        $suffix = explode(‘/‘,$mime)[1];
    }
    return $suffix;
    }
  2. 測試:
    $suffix = getimgsuffix(‘http://192.168.8.81/public/image/01.jpg‘);
    echo $suffix;
  3. 輸出:
    jpeg

    二、二進制方法:

  4. 代碼:
    <?php
    /*
    @desc:獲取文件真實後綴
    @param   name    文件名
    @return  suffix  文件後綴
    */   
    function getfilesuffix($name) {
    $file = fopen($name, "rb");
    $bin = fread($file, 2); // 只讀2字節
    fclose($file);
    $info = @unpack("C2chars", $bin);
    $code = intval($info[‘chars1‘] . $info[‘chars2‘]);
    $suffix = "unknow";
    if($code == 255216){
        $suffix = "jpg";
    }elseif($code == 7173){
        $suffix = "gif";
    }elseif($code == 13780){
        $suffix = "png";
    }elseif($code == 6677){
        $suffix = "bmp";
    }elseif($code == 7798){
        $suffix = "exe";
    }elseif($code == 7784){
        $suffix = "midi";
    }elseif($code == 8297){
        $suffix = "rar";
    }elseif($code == 7368){
        $suffix = "mp3";
    }elseif($code == 0){
        $suffix = "mp4";
    }elseif($code == 8273){
        $suffix = "wav";
    }
    return $suffix;
    }
  5. 測試:
    $suffix = getfilesuffix(‘http://192.168.8.81/public/image/01.jpg‘);
    echo $suffix;
  6. 輸出:
    jpg

php獲取圖片真實後綴的兩種方法