天天看點

php判斷檔案上傳圖檔格式是否為圖檔

判斷檔案圖檔類型,

$type     = $_FILES['image']['tmp_name'];//檔案名
  //$type     = $this->getImagetype( $type ); 
  $filetype = ['jpg', 'jpeg', 'gif', 'bmp', 'png'];
  if (! in_array($type, $filetype))
  {  
        return "不是圖檔類型";
  }
           

如上如果使用者修改檔案字尾為png jpeg等無法滿足,查了查資料解決方法是采用判斷檔案的二進制流資訊,如果你剛好遇到這種問題不妨嘗試一下:

//*判斷圖檔上傳格式是否為圖檔 return傳回檔案字尾
    public function getImagetype($filename)
    {
        $file = fopen($filename, 'rb');
        $bin  = fread($file, ); //隻讀位元組
        fclose($file);
        $strInfo  = @unpack('C2chars', $bin);
        $typeCode = intval($strInfo['chars1'].$strInfo['chars2']);
        // dd($typeCode);
        $fileType = '';
        switch ($typeCode) {
            case :
                $fileType = 'jpg';
                break;
            case :
                $fileType = 'gif';
                break;
            case :
                $fileType = 'bmp';
                break;
            case :
                $fileType = 'png';
                break;
            default:
                $fileType = '隻能上傳圖檔類型格式';
        }
        // if ($strInfo['chars1']=='-1' AND $strInfo['chars2']=='-40' ) return 'jpg';
        // if ($strInfo['chars1']=='-119' AND $strInfo['chars2']=='80' ) return 'png';
        return $fileType;
    }
           

如果對你有幫助,頂我一下,謝謝!