php获取上传文件类型 获取文件后缀

本教程提供了三款获取上传文件与图片类型的方法,方法也是很简单的前二种,是先把类型定义好,再用in_array判断,最后一步是利用了fopen再读取前二个字节,判断.

代码如下:

  1. //获得图片的格式,包括jpg,png,gif
  2. function get_type($img_name)//获取图像文件类型
  3. {
  4. if (preg_match("/.(jpg|jpeg|gif|png|bmp)$/i", $img_name, $matches)){
  5. $type = strtolower($matches[1]);
  6. }else{
  7. $type = "string";
  8. }
  9. return $type;
  10. }
  11. //判断上传文件类型
  12. $allowedextensions = array("txt","csv","htm","html","xml",
  13. "css教程","doc","xls","rtf","ppt","pdf","swf","flv","avi",
  14. "wmv","mov","jpg","jpeg","gif","png");
  15. foreach ($_files as $file) {
  16. if ($file['tmp_name'] > '') {
  17. if (!in_array(end(explode(".",
  18. strtolower($file['name']))),
  19. $allowedextensions)) {
  20. die($file['name'].' is an invalid file type!<br/>'.
  21. '<a href="网页特效:history.go(-1);">'.
  22. '&lt;&lt go back</a>');
  23. }
  24. }
  25. }
  26. //另类的读取文件与图片类型
  27. function checktitle($filename) {
  28. $file = fopen($filename, "rb");
  29. $bin = fread($file, 2); //只读2字节
  30. fclose($file);
  31. $strinfo = @unpack("c2chars", $bin);
  32. $typecode = intval($strinfo['chars1'].$strinfo['chars2']);
  33. $filetype = "";
  34. switch ($typecode)
  35. {
  36. case 7790:
  37. $filetype = 'exe';
  38. break;
  39. case 7784:
  40. $filetype = 'midi';
  41. break;
  42. case 8297:
  43. $filetype = 'rar';
  44. break;
  45. case 255216:
  46. $filetype = 'jpg';
  47. break;
  48. case 7173:
  49. $filetype = 'gif';
  50. break;
  51. case 6677:
  52. $filetype = 'bmp';
  53. break;
  54. case 13780:
  55. $filetype = 'png';
  56. break;
  57. default:
  58. $filetype = 'unknown'.$typecode;
  59. }
  60. //fix
  61. if ($strinfo['chars1']=='-1' && $strinfo['chars2']=='-40' ) {
  62. return 'jpg';
  63. }
  64. if ($strinfo['chars1']=='-119' && $strinfo['chars2']=='80' ) {
  65. return 'png';
  66. }
  67. return $filetype;
  68. }
  69. ?>