php获得上传文件类型的几种方法

1、mime_content_type()函数判断获取文件类型

mime_content_type返回指定文件的MIME类型,

用法:

1 echomime_content_type('php.gif') ."n";

echomime_content_type('test.php');

输出:

image/gif

text/plain

但是php 5.3.0已经将该函数废弃。如果仍想使用此函数,那么可以对php进行配置启用magic_mime扩展。

2、php Fileinfo 获取文件类型(finfo_open)

PHP官方推荐mime_content_type()的替代函数是Fileinfo函数。PHP 5.3.0+已经默认支持Fileinfo函数(fileinfo support-enabled),不必进行任何配置即可使用finfo_open()判断获取文件MIME类型。

用法代码如下:

  1. $finfo = finfo_open(FILEINFO_MIME);
  2. $mimetype = finfo_file($finfo, $filename);
  3. finfo_close($finfo);

3、image_type_to_mime_type()获取图片类型

如果需要判断MIME类型的文件只有图像文件,那么首先可以使用exif_imagetype()函数获取图像类型常量,再用image_type_to_mime_type()函数将图像类型常量转换成图片文件的MIME类型。

注意:

需要在php.ini中配置打开php_mbstring.dll (Windows需要)和extension=php_exif.dll。

4、php获取上传文件类型

如果使用php上传文件,检测上传文件的MIME类型,则可以使用全局变量$_FILES['uploadfile']['type'],由客户端的浏览器检测获取文件MIME类型。

下面直接上代码,相信略有些php功底的朋友,读来都不成问题,我实现的是仅支持word和pdf文件,且文件大小小于512kb:

  1. $tmpname = $_FILES ['userfile'] ['tmp_name'];
  2. if(is_uploaded_file($tmpname)) {
  3. $mimetype = detectMIME($tmpname);
  4. $tuozhanming = getFileExt($filename, $mimetype);
  5. if($tuozhanming == "type_error"){
  6. echo '仅支持word和pdf文件,且文件大小小于512kb:<a href='.$reurl.'>请重试</a>';
  7. exit();
  8. }
  9. }else{
  10. $_FILES ['userfile'] ['error'] = 6;
  11. }
  12. if ($_FILES ['userfile'] ['error'] > 0) {
  13. echo 'Problem: ';
  14. switch ($_FILES ['userfile'] ['error']) {
  15. case 1 :
  16. echo '上传文件过大:<a href='.$reurl.'>请重试</a>';
  17. break;
  18. case 2 :
  19. echo '上传文件过大:<a href='.$reurl.'>请重试</a>';
  20. break;
  21. case 3 :
  22. echo '文件上传丢失:<a href='.$reurl.'>请重试</a>';
  23. break;
  24. case 4 :
  25. echo '无文件被上传:<a href='.$reurl.'>请重试</a>';
  26. break;
  27. case 6 :
  28. echo '仅支持word和pdf文件,且文件大小小于512kb:<a href='.$reurl.'>请重试</a>';
  29. break;
  30. case 7 :
  31. echo '上传文件存储失败:<a href='.$reurl.'>请重试</a>';
  32. break;
  33. }
  34. exit ();
  35. }
  36. //判断文件类型
  37. //上传文件
  38. $_FILES ['userfile'] ['name'] = time () . "." . $tuozhanming;
  39. $upfile = '../uploads/' . $_FILES ['userfile'] ['name'];
  40. if ( !move_uploaded_file ( $_FILES ['userfile'] ['tmp_name'], $upfile )) {
  41. echo 'Problem: 文件移动失败';
  42. exit ();
  43. }
  44. }
  45. function detectMIME($filename) {
  46. $file = fopen ( $filename, "rb" );
  47. $finfo = finfo_open ( FILEINFO_MIME );
  48. if (! $finfo) {
  49. // 直接读取文件的前4个字节,根据硬编码判断
  50. $file = fopen ( $filename, "rb" );
  51. $bin = fread ( $file, 4 ); //只读文件头4字节
  52. fclose ( $file );
  53. $strInfo = @unpack ( "C4chars", $bin );
  54. //dechex() 函数把十进制转换为十六进制。
  55. $typeCode = dechex ( $strInfo ['chars1'] ) .
  56. dechex ( $strInfo ['chars2'] ) .
  57. dechex ( $strInfo ['chars3'] ) .
  58. dechex ( $strInfo ['chars4'] );
  59. $type = '';
  60. switch ($typeCode) //硬编码值查表
  61. {
  62. case "504b34" :
  63. $type = 'application/zip; charset=binary';
  64. break;
  65. case "d0cf11e0" :
  66. $type = 'application/vnd.ms-office; charset=binary';
  67. break;
  68. case "25504446" :
  69. $type = 'application/pdf; charset=binary';
  70. break;
  71. default :
  72. $type = 'application/vnd.ms-office; charset=binary';
  73. break;
  74. }
  75. } else {
  76. //finfo_file return information of a file
  77. $type = finfo_file ( $finfo, $filename );
  78. }
  79. return $type;
  80. function getFileExt($filename, $type) {
  81. switch ($type) {
  82. case "application/zip; charset=binary" :
  83. $extType = "docx";
  84. break;
  85. case "application/vnd.ms-office; charset=binary" :
  86. $extType = "doc";
  87. break;
  88. case "application/msword; charset=binary" :
  89. $extType = "doc";
  90. break;
  91. case "application/pdf; charset=binary" :
  92. $extType = "pdf";
  93. break;
  94. default :
  95. $extType = "type_error";
  96. break;
  97. }
  98. return $extType;
  99. }

方法五,网上流传一段PHP读取文件头判断文件类型的方法,有一些bug,经我(54chen)修改实测,应该是这个样子:

  1. /**
  2. * 读取文件前几个字节 判断文件类型
  3. *
  4. * @return String
  5. */
  6. function checkTitle($filename) {
  7. $file = fopen($filename, "rb");
  8. $bin = fread($file, 2); //只读2字节
  9. fclose($file);
  10. $strInfo = @unpack("c2chars", $bin);
  11. $typeCode = intval($strInfo['chars1'].$strInfo['chars2']);
  12. $fileType = '';
  13. switch ($typeCode)
  14. {
  15. case 7790:
  16. $fileType = 'exe';
  17. break;
  18. case 7784:
  19. $fileType = 'midi';
  20. break;
  21. case 8297:
  22. $fileType = 'rar';
  23. break;
  24. case 255216:
  25. $fileType = 'jpg';
  26. break;
  27. case 7173:
  28. $fileType = 'gif';
  29. break;
  30. case 6677:
  31. $fileType = 'bmp';
  32. break;
  33. case 13780:
  34. $fileType = 'png';
  35. break;
  36. default:
  37. $fileType = 'unknown'.$typeCode;
  38. }
  39. //Fix
  40. if ($strInfo['chars1']=='-1' && $strInfo['chars2']=='-40' ) {
  41. return 'jpg';
  42. }
  43. if ($strInfo['chars1']=='-119' && $strInfo['chars2']=='80' ) {
  44. return 'png';
  45. }
  46. return $fileType;
  47. }

对于上传文件类型的判断,一直没有太好的办法,即使使用上面的代码,也有办法构造假的图片的(如何构造不再传播),有人使用getimagesize来判断,不失为一种好办法:

  1. if(in_array($attach['ext'], array('jpg', 'jpeg', 'gif', 'png', 'swf', 'bmp')) && function_exists('getimagesize') && !@getimagesize($target)) {
  2. @unlink($target);
  3. upload_error('post_attachment_ext_notallowed', $attacharray);
  4. }

补充:文件类型 值大全:

  1. 123 application/vnd.lotus-1-2-3
  2. 3gp video/3gpp
  3. aab application/x-authoware-bin
  4. aam application/x-authoware-map
  5. aas application/x-authoware-seg
  6. ai application/postscript
  7. aif audio/x-aiff
  8. aifc audio/x-aiff
  9. aiff audio/x-aiff
  10. als audio/X-Alpha5
  11. amc application/x-mpeg
  12. ani application/octet-stream
  13. asc text/plain
  14. asd application/astound
  15. asf video/x-ms-asf
  16. asn application/astound
  17. asp application/x-asap
  18. asx video/x-ms-asf
  19. au audio/basic
  20. avb application/octet-stream
  21. avi video/x-msvideo
  22. awb audio/amr-wb
  23. bcpio application/x-bcpio
  24. bin application/octet-stream
  25. bld application/bld
  26. bld2 application/bld2
  27. bmp application/x-MS-bmp
  28. bpk application/octet-stream
  29. bz2 application/x-bzip2
  30. cal image/x-cals
  31. ccn application/x-cnc
  32. cco application/x-cocoa
  33. cdf application/x-netcdf
  34. cgi magnus-internal/cgi
  35. chat application/x-chat
  36. class application/octet-stream
  37. clp application/x-msclip
  38. cmx application/x-cmx
  39. co application/x-cult3d-object
  40. cod image/cis-cod
  41. cpio application/x-cpio
  42. cpt application/mac-compactpro
  43. crd application/x-mscardfile
  44. csh application/x-csh
  45. csm chemical/x-csml
  46. csml chemical/x-csml
  47. css text/css
  48. cur application/octet-stream
  49. dcm x-lml/x-evm
  50. dcr application/x-director
  51. dcx image/x-dcx
  52. dhtml text/html
  53. dir application/x-director
  54. dll application/octet-stream
  55. dmg application/octet-stream
  56. dms application/octet-stream
  57. doc application/msword
  58. dot application/x-dot
  59. dvi application/x-dvi
  60. dwf drawing/x-dwf
  61. dwg application/x-autocad
  62. dxf application/x-autocad
  63. dxr application/x-director
  64. ebk application/x-expandedbook
  65. emb chemical/x-embl-dl-nucleotide
  66. embl chemical/x-embl-dl-nucleotide
  67. eps application/postscript
  68. eri image/x-eri
  69. es audio/echospeech
  70. esl audio/echospeech
  71. etc application/x-earthtime
  72. etx text/x-setext
  73. evm x-lml/x-evm
  74. evy application/x-envoy
  75. exe application/octet-stream
  76. fh4 image/x-freehand
  77. fh5 image/x-freehand
  78. fhc image/x-freehand
  79. fif image/fif
  80. fm application/x-maker
  81. fpx image/x-fpx
  82. fvi video/isivideo
  83. gau chemical/x-gaussian-input
  84. gca application/x-gca-compressed
  85. gdb x-lml/x-gdb
  86. gif image/gif
  87. gps application/x-gps
  88. gtar application/x-gtar
  89. gz application/x-gzip
  90. hdf application/x-hdf
  91. hdm text/x-hdml
  92. hdml text/x-hdml
  93. hlp application/winhlp
  94. hqx application/mac-binhex40
  95. htm text/html
  96. html text/html
  97. hts text/html
  98. ice x-conference/x-cooltalk
  99. ico application/octet-stream
  100. ief image/ief
  101. ifm image/gif
  102. ifs image/ifs
  103. imy audio/melody
  104. ins application/x-NET-Install
  105. ips application/x-ipscript
  106. ipx application/x-ipix
  107. it audio/x-mod
  108. itz audio/x-mod
  109. ivr i-world/i-vrml
  110. j2k image/j2k
  111. jad text/vnd.sun.j2me.app-descriptor
  112. jam application/x-jam
  113. jar application/java-archive
  114. jnlp application/x-java-jnlp-file
  115. jpe image/jpeg
  116. jpeg image/jpeg
  117. jpg image/jpeg
  118. jpz image/jpeg
  119. js application/x-javascript
  120. jwc application/jwc
  121. kjx application/x-kjx
  122. lak x-lml/x-lak
  123. latex application/x-latex
  124. lcc application/fastman
  125. lcl application/x-digitalloca
  126. lcr application/x-digitalloca
  127. lgh application/lgh
  128. lha application/octet-stream
  129. lml x-lml/x-lml
  130. lmlpack x-lml/x-lmlpack
  131. lsf video/x-ms-asf
  132. lsx video/x-ms-asf
  133. lzh application/x-lzh
  134. m13 application/x-msmediaview
  135. m14 application/x-msmediaview
  136. m15 audio/x-mod
  137. m3u audio/x-mpegurl
  138. m3url audio/x-mpegurl
  139. ma1 audio/ma1
  140. ma2 audio/ma2
  141. ma3 audio/ma3
  142. ma5 audio/ma5
  143. man application/x-troff-man
  144. map magnus-internal/imagemap
  145. mbd application/mbedlet
  146. mct application/x-mascot
  147. mdb application/x-msaccess
  148. mdz audio/x-mod
  149. me application/x-troff-me
  150. mel text/x-vmel
  151. mi application/x-mif
  152. mid audio/midi
  153. midi audio/midi
  154. mif application/x-mif
  155. mil image/x-cals
  156. mio audio/x-mio
  157. mmf application/x-skt-lbs
  158. mng video/x-mng
  159. mny application/x-msmoney
  160. moc application/x-mocha
  161. mocha application/x-mocha
  162. mod audio/x-mod
  163. mof application/x-yumekara
  164. mol chemical/x-mdl-molfile
  165. mop chemical/x-mopac-input
  166. mov video/quicktime
  167. movie video/x-sgi-movie
  168. mp2 audio/x-mpeg
  169. mp3 audio/x-mpeg
  170. mp4 video/mp4
  171. mpc application/vnd.mpohun.certificate
  172. mpe video/mpeg
  173. mpeg video/mpeg
  174. mpg video/mpeg
  175. mpg4 video/mp4
  176. mpga audio/mpeg
  177. mpn application/vnd.mophun.application
  178. mpp application/vnd.ms-project
  179. mps application/x-mapserver
  180. mrl text/x-mrml
  181. mrm application/x-mrm
  182. ms application/x-troff-ms
  183. mts application/metastream
  184. mtx application/metastream
  185. mtz application/metastream
  186. mzv application/metastream
  187. nar application/zip
  188. nbmp image/nbmp
  189. nc application/x-netcdf
  190. ndb x-lml/x-ndb
  191. ndwn application/ndwn
  192. nif application/x-nif
  193. nmz application/x-scream
  194. nokia-op-logo image/vnd.nok-oplogo-color
  195. npx application/x-netfpx
  196. nsnd audio/nsnd
  197. nva application/x-neva1
  198. oda application/oda
  199. oom application/x-AtlasMate-Plugin
  200. pac audio/x-pac
  201. pae audio/x-epac
  202. pan application/x-pan
  203. pbm image/x-portable-bitmap
  204. pcx image/x-pcx
  205. pda image/x-pda
  206. pdb chemical/x-pdb
  207. pdf application/pdf
  208. pfr application/font-tdpfr
  209. pgm image/x-portable-graymap
  210. pict image/x-pict
  211. pm application/x-perl
  212. pmd application/x-pmd
  213. png image/png
  214. pnm image/x-portable-anymap
  215. pnz image/png
  216. pot application/vnd.ms-powerpoint
  217. ppm image/x-portable-pixmap
  218. pps application/vnd.ms-powerpoint
  219. ppt application/vnd.ms-powerpoint
  220. pqf application/x-cprplayer
  221. pqi application/cprplayer
  222. prc application/x-prc
  223. proxy application/x-ns-proxy-autoconfig
  224. ps application/postscript
  225. ptlk application/listenup
  226. pub application/x-mspublisher
  227. pvx video/x-pv-pvx
  228. qcp audio/vnd.qcelp
  229. qt video/quicktime
  230. qti image/x-quicktime
  231. qtif image/x-quicktime
  232. r3t text/vnd.rn-realtext3d
  233. ra audio/x-pn-realaudio
  234. ram audio/x-pn-realaudio
  235. rar application/x-rar-compressed
  236. ras image/x-cmu-raster
  237. rdf application/rdf+xml
  238. rf image/vnd.rn-realflash
  239. rgb image/x-rgb
  240. rlf application/x-richlink
  241. rm audio/x-pn-realaudio
  242. rmf audio/x-rmf
  243. rmm audio/x-pn-realaudio
  244. rmvb audio/x-pn-realaudio
  245. rnx application/vnd.rn-realplayer
  246. roff application/x-troff
  247. rp image/vnd.rn-realpix
  248. rpm audio/x-pn-realaudio-plugin
  249. rt text/vnd.rn-realtext
  250. rte x-lml/x-gps
  251. rtf application/rtf
  252. rtg application/metastream
  253. rtx text/richtext
  254. rv video/vnd.rn-realvideo
  255. rwc application/x-rogerwilco
  256. s3m audio/x-mod
  257. s3z audio/x-mod
  258. sca application/x-supercard
  259. scd application/x-msschedule
  260. sdf application/e-score
  261. sea application/x-stuffit
  262. sgm text/x-sgml
  263. sgml text/x-sgml
  264. sh application/x-sh
  265. shar application/x-shar
  266. shtml magnus-internal/parsed-html
  267. shw application/presentations
  268. si6 image/si6
  269. si7 image/vnd.stiwap.sis
  270. si9 image/vnd.lgtwap.sis
  271. sis application/vnd.symbian.install
  272. sit application/x-stuffit
  273. skd application/x-Koan
  274. skm application/x-Koan
  275. skp application/x-Koan
  276. skt application/x-Koan
  277. slc application/x-salsa
  278. smd audio/x-smd
  279. smi application/smil
  280. smil application/smil
  281. smp application/studiom
  282. smz audio/x-smd
  283. snd audio/basic
  284. spc text/x-speech
  285. spl application/futuresplash
  286. spr application/x-sprite
  287. sprite application/x-sprite
  288. spt application/x-spt
  289. src application/x-wais-source
  290. stk application/hyperstudio
  291. stm audio/x-mod
  292. sv4cpio application/x-sv4cpio
  293. sv4crc application/x-sv4crc
  294. svf image/vnd
  295. svg image/svg-xml
  296. svh image/svh
  297. svr x-world/x-svr
  298. swf application/x-shockwave-flash
  299. swfl application/x-shockwave-flash
  300. t application/x-troff
  301. tad application/octet-stream
  302. talk text/x-speech
  303. tar application/x-tar
  304. taz application/x-tar
  305. tbp application/x-timbuktu
  306. tbt application/x-timbuktu
  307. tcl application/x-tcl
  308. tex application/x-tex
  309. texi application/x-texinfo
  310. texinfo application/x-texinfo
  311. tgz application/x-tar
  312. thm application/vnd.eri.thm
  313. tif image/tiff
  314. tiff image/tiff
  315. tki application/x-tkined
  316. tkined application/x-tkined
  317. toc application/toc
  318. toy image/toy
  319. tr application/x-troff
  320. trk x-lml/x-gps
  321. trm application/x-msterminal
  322. tsi audio/tsplayer
  323. tsp application/dsptype
  324. tsv text/tab-separated-values
  325. tsv text/tab-separated-values
  326. ttf application/octet-stream
  327. ttz application/t-time
  328. txt text/plain
  329. ult audio/x-mod
  330. ustar application/x-ustar
  331. uu application/x-uuencode
  332. uue application/x-uuencode
  333. vcd application/x-cdlink
  334. vcf text/x-vcard
  335. vdo video/vdo
  336. vib audio/vib
  337. viv video/vivo
  338. vivo video/vivo
  339. vmd application/vocaltec-media-desc
  340. vmf application/vocaltec-media-file
  341. vmi application/x-dreamcast-vms-info
  342. vms application/x-dreamcast-vms
  343. vox audio/voxware
  344. vqe audio/x-twinvq-plugin
  345. vqf audio/x-twinvq
  346. vql audio/x-twinvq
  347. vre x-world/x-vream
  348. vrml x-world/x-vrml
  349. vrt x-world/x-vrt
  350. vrw x-world/x-vream
  351. vts workbook/formulaone
  352. wav audio/x-wav
  353. wax audio/x-ms-wax
  354. wbmp image/vnd.wap.wbmp
  355. web application/vnd.xara
  356. wi image/wavelet
  357. wis application/x-InstallShield
  358. wm video/x-ms-wm
  359. wma audio/x-ms-wma
  360. wmd application/x-ms-wmd
  361. wmf application/x-msmetafile
  362. wml text/vnd.wap.wml
  363. wmlc application/vnd.wap.wmlc
  364. wmls text/vnd.wap.wmlscript
  365. wmlsc application/vnd.wap.wmlscriptc
  366. wmlscript text/vnd.wap.wmlscript
  367. wmv audio/x-ms-wmv
  368. wmx video/x-ms-wmx
  369. wmz application/x-ms-wmz
  370. wpng image/x-up-wpng
  371. wpt x-lml/x-gps
  372. wri application/x-mswrite
  373. wrl x-world/x-vrml
  374. wrz x-world/x-vrml
  375. ws text/vnd.wap.wmlscript
  376. wsc application/vnd.wap.wmlscriptc
  377. wv video/wavelet
  378. wvx video/x-ms-wvx
  379. wxl application/x-wxl
  380. x-gzip application/x-gzip
  381. xar application/vnd.xara
  382. xbm image/x-xbitmap
  383. xdm application/x-xdma
  384. xdma application/x-xdma
  385. xdw application/vnd.fujixerox.docuworks
  386. xht application/xhtml+xml
  387. xhtm application/xhtml+xml
  388. xhtml application/xhtml+xml
  389. xla application/vnd.ms-excel
  390. xlc application/vnd.ms-excel
  391. xll application/x-excel
  392. xlm application/vnd.ms-excel
  393. xls application/vnd.ms-excel
  394. xlt application/vnd.ms-excel
  395. xlw application/vnd.ms-excel
  396. xm audio/x-mod
  397. xml text/xml
  398. xmz audio/x-mod
  399. xpi application/x-xpinstall
  400. xpm image/x-xpixmap
  401. xsit text/xml
  402. xsl text/xml
  403. xul text/xul
  404. xwd image/x-xwindowdump
  405. xyz chemical/x-pdb
  406. yz1 application/x-yz1
  407. z application/x-compress
  408. zac application/x-zaurus-zac
  409. zip application/zip