php判断文件上传图片格式的实例详解

yipeiwu_com5年前PHP代码库

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, 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;
 }

如有疑问请留言或者到本站社区交流讨论,感谢阅读,希望能帮助到大家,谢谢大家对本站的支持!

相关文章

PHP面向对象精要总结

本文实例汇总了PHP面向对象程序设计的精要。分享给大家供大家参考。具体分析如下: 1 使用extends实现继承以及重载、魔术方法的含义 class B extends A 声明的时候B...

PHP Class&Object -- 解析PHP实现二叉树

二叉树及其变体是数据结构家族里的重要组成部分。最为链表的一种变体,二叉树最适合处理需要一特定次序快速组织和检索的数据。复制代码 代码如下:<?php// Define a clas...

php json_encode奇怪问题说明

json_encode 只支持utf-8格式这个就不多说了 复制代码 代码如下: $array = array ( [0] => array ( [sale_unit_detail...

file_get_contents(&quot;php://input&quot;, &quot;r&quot;)实例介绍

file_get_contents(&quot;php://input&quot;, &quot;r&quot;)实例介绍

解释不清,直接上例子index.html复制代码 代码如下:  <form action="action.php" method="post" >  &l...

escape unescape的php下的实现方法

function escape($str) {   preg_match_all("/[\x80-\xff].|[\x01-\x7f]+/",$s...