Php code for determining the file type to be uploaded-php Tutorial

Source: Internet
Author: User
An example of php code used to determine the file upload type

  1. /**
  2. * Determine the type of the uploaded file
  3. * Edit bbs.it-home.org
  4. */
  5. Function file_type ($ filename)
  6. {
  7. $ File = fopen ($ filename, "rb ");
  8. $ Bin = fread ($ file, 2); // read-only 2 bytes
  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 8075:
  25. $ FileType = 'Zip ';
  26. Break;
  27. Case 255216:
  28. $ FileType = 'jpg ';
  29. Break;
  30. Case 7173:
  31. $ FileType = 'GIF ';
  32. Break;
  33. Case 6677:
  34. $ FileType = 'bmp ';
  35. Break;
  36. Case 13780:
  37. $ FileType = 'PNG ';
  38. Break;
  39. Default:
  40. $ FileType = 'unknown: '. $ typeCode;
  41. }
  42. // Fix
  43. If ($ strInfo ['chars1'] = '-1' AND $ strInfo ['chars2'] ='-40') return 'jpg ';
  44. If ($ strInfo ['chars1'] = '-119' AND $ strInfo ['chars2'] = '80') return 'PNG ';
  45. Return $ fileType;
  46. }
  47. // Call
  48. Echo file_type ('Start. php'); // 6063 or 6033
  49. ?>

I don't know if the definition of 6063 or 6033 in turn refers to php is not rigorous enough.

The above code does not make a good decision on the file type for constructing fake images. In this case, you can consider using getimagesize to determine. the reference code is as follows:

  1. /**
  2. * Getimagesize determines the file type
  3. * Edit bbs.it-home.org
  4. */
  5. If (in_array ($ attach ['ext '], array ('jpg', 'jpeg ', 'GIF', 'PNG', 'swf ', 'bmp ')) & function_exists ('getimagesize ')&&! @ Getimagesize ($ target ))
  6. {
  7. Unlink ($ target );
  8. Upload_error ('post _ attachment_ext_notallowed ', $ attacharray );
  9. }
  10. ?>

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.