Two ways to get the true suffix of a picture in PHP

Source: Internet
Author: User

First, getimagesize (support base64):
  1. Code:
    <?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. Test:
    $suffix = getimgsuffix(‘http://192.168.8.81/public/image/01.jpg‘);echo $suffix;
  3. Output:
    jpeg
    Second, binary method:
  4. Code:
    <?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. Test:
    $suffix = getfilesuffix(‘http://192.168.8.81/public/image/01.jpg‘);echo $suffix;
  6. Output:
    jpg

Two ways to get the true suffix of a picture in PHP

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.