Introduction to the method of determining the image format of file upload in PHP

黄舟
Release: 2023-03-16 14:36:01
Original
2734 people have browsed it

This article mainly introduces relevant information about the detailed explanation of the example of PHP judging the file upload image format. I hope this article can help everyone implement this method. It is very valuable for reference. Friends in need can refer to it

php Detailed example of determining the file upload image format

Determine the file image type,


##

 $type  = $_FILES['image']['tmp_name'];//文件名
 //$type  = $this->getImagetype( $type ); 
 $filetype = ['jpg', 'jpeg', 'gif', 'bmp', 'png'];
 if (! in_array($type, $filetype))
 { 
  return "不是图片类型";
 }
Copy after login

As above, if the user modifies the file suffix to png jpeg If you can't satisfy it, I checked the information and the solution is to use the binary stream information of the file to judge. If you happen to encounter this kind of problem, you might as well try it:


 //*判断图片上传格式是否为图片 return返回文件后缀
 public function getImagetype($filename)
 {
  $file = fopen($filename, 'rb');
  $bin = fread($file, 2); //只读2字节
  fclose($file);
  $strInfo = @unpack('C2chars', $bin);
  $typeCode = intval($strInfo['chars1'].$strInfo['chars2']);
  // dd($typeCode);
  $fileType = '';
  switch ($typeCode) {
   case 255216:
    $fileType = 'jpg';
    break;
   case 7173:
    $fileType = 'gif';
    break;
   case 6677:
    $fileType = 'bmp';
    break;
   case 13780:
    $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;
 }
Copy after login

The above is the detailed content of Introduction to the method of determining the image format of file upload in PHP. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template