Several ways to get uploaded file types in PHP

Source: Internet
Author: User
Tags file upload fread php read file rar unpack zip gtar

1, Mime_content_type () function to judge get file type

Mime_content_type returns the MIME type of the specified file.

Usage:

The code is as follows Copy Code

Echomime_content_type (' Php.gif '). " n ";
Echomime_content_type (' test.php ');
Output:
Image/gif
Text/plain

But PHP 5.3.0 has discarded the function. If you still want to use this function, you can configure PHP to enable Magic_mime extensions.

2, PHP Fileinfo get file type (Finfo_open)

An alternative function of the official PHP recommendation Mime_content_type () is the FileInfo function. The PHP 5.3.0+ already supports the FileInfo function (FileInfo support-enabled) By default and can use Finfo_open () to determine the file MIME type without any configuration.
Usage:

The code is as follows Copy Code

$finfo = Finfo_open (fileinfo_mime);
$mimetype = Finfo_file ($finfo, $filename);
Finfo_close ($finfo);

3. Image_type_to_mime_type () Get Picture type

If you need to determine a MIME-type file with only an image file, you can first use the Exif_imagetype () function to get the image type constant, and then use the Image_type_to_mime_type () function to convert the image type constant to the MIME type of the picture file.
Attention:

You need to configure open Php_mbstring.dll (Windows required) and Extension=php_exif.dll in php.ini.

4, PHP get upload file type

If you use PHP to upload a file and detect the MIME type of the uploaded file, you can use the global variable $_files[' uploadfile ' [' type '], which is detected by the client's browser to get the file MIME type.

The following directly on the code, I believe that a little bit of PHP knowledge of friends, read is not a problem. I realized that only word and PDF files are supported, and the file size is less than 512KB:

The code is as follows Copy Code


$tmpname = $_files [' userfile '] [' tmp_name '];
if (Is_uploaded_file ($tmpname)) {
$mimetype = Detectmime ($tmpname);
$tuozhanming = Getfileext ($filename, $mimetype);
if ($tuozhanming = = "Type_error") {
echo ' only supports Word and PDF files, and the file size is less than 512kb:<a href= '. $reurl. ' > Please retry </a> ';
Exit ();
}
}else{
$_files [' UserFile '] [' error '] = 6;
}

if ($_files [' userfile '] [' ERROR '] &gt; 0) {


Echo ' Problem: ';


Switch ($_files [' userfile '] [' ERROR ']) {


Case 1:


echo ' Upload file too large: &lt;a href= '. $reurl. ' &gt; Please retry &lt;/a&gt; ';


Break


Case 2:


echo ' Upload file too large: &lt;a href= '. $reurl. ' &gt; Please retry &lt;/a&gt; ';


Break


Case 3:


echo ' File upload lost: &lt;a href= '. $reurl. ' &gt; Please retry &lt;/a&gt; ';


Break


Case 4:


Echo ' no file uploaded: &lt;a href= '. $reurl. ' &gt; Please retry &lt;/a&gt; ';


Break


Case 6:


echo ' only supports Word and PDF files, and the file size is less than 512kb:&lt;a href= '. $reurl. ' &gt; Please retry &lt;/a&gt; ';


Break


Case 7:


echo ' upload file Store failed: &lt;a href= '. $reurl. ' &gt; Please retry &lt;/a&gt; ';


Break


}


Exit ();


}


Determining File Types


Uploading files


$_files [' UserFile '] [' name '] = time (). "." . $tuozhanming;


$upfile = '. /uploads/'. $_files [' UserFile '] [' name '];

if (!move_uploaded_file ($_files [' userfile '] [' tmp_name '], $upfile)) {
Echo ' Problem: File move failed ';
Exit ();
}

}

function Detectmime ($filename) {


$file = fopen ($filename, "RB");


$finfo = Finfo_open (fileinfo_mime);


if (! $finfo) {


Read directly the first 4 bytes of the file, judging by hard coding


$file = fopen ($filename, "RB");


$bin = Fread ($file, 4); Read-only file header 4 bytes


Fclose ($file);


$strInfo = @unpack ("C4chars", $bin);


The Dechex () function converts the decimal system to 16.


$typeCode = Dechex ($strInfo [' chars1 ']).


Dechex ($strInfo [' chars2 ']).


Dechex ($strInfo [' Chars3 ']).


Dechex ($strInfo [' chars4 ']);


$type = ';


Switch ($typeCode)//Hard coded value look-up table


{


Case "504b34":


$type = ' Application/zip; Charset=binary ';


Break


Case "D0CF11E0":


$type = ' Application/vnd.ms-office; Charset=binary ';


Break


Case "25504446":


$type = ' application/pdf; Charset=binary ';


Break


Default:


$type = ' Application/vnd.ms-office; Charset=binary ';


Break


}


} else {


Finfo_file return information of a file


$type = Finfo_file ($finfo, $filename);


}


return $type;

function Getfileext ($filename, $type) {
Switch ($type) {
Case "APPLICATION/ZIP; Charset=binary ":
$extType = "docx";
Break
Case "Application/vnd.ms-office; Charset=binary ":
$extType = "Doc";
Break
Case "Application/msword; Charset=binary ":
$extType = "Doc";
Break
Case "application/pdf; Charset=binary ":
$extType = "PDF";
Break
Default:
$extType = "Type_error";
Break
}
return $extType;
}

method Five, the Internet circulated a section of PHP read file header to determine the type of file, there are some bugs, after I (54chen) modify the measurement, it should be this way:

The code is as follows Copy Code
/**


* Read the file before the first few bytes to determine the file type


*


* @return String


*/


function Checktitle ($filename) {


$file = fopen ($filename, "RB");


$bin = Fread ($file, 2); Read Only 2 bytes


Fclose ($file);


$strInfo = @unpack ("C2chars", $bin);


$typeCode = Intval ($strInfo [' chars1 ']. $strInfo [' chars2 ']);


$fileType = ';


Switch ($typeCode)


{


Case 7790:


$fileType = ' exe ';


Break


Case 7784:


$fileType = ' midi ';


Break


Case 8297:


$fileType = ' rar ';


Break


Case 255216:


$fileType = ' jpg ';


Break


Case 7173:


$fileType = ' gif ';


Break


Case 6677:


$fileType = ' bmp ';


Break


Case 13780:


$fileType = ' png ';


Break


Default


$fileType = ' unknown '. $typeCode;


}


Fix


if ($strInfo [' chars1 ']== '-1 ' &amp;&amp; $strInfo [' chars2 ']== '-40 ') {


return ' jpg ';


}


if ($strInfo [' chars1 ']== ' -119 ' &amp;&amp; $strInfo [' chars2 ']== ' 80 ') {


return ' PNG ';


}


return $fileType;


}



For the upload file type judgment, has not been very good method, even if uses the above code, also has the method constructs the false picture (how constructs no longer spreads), some people use getimagesize to judge, is a good method:

The code is as follows Copy Code

if (In_array ($attach [' ext '], array (' jpg ', ' jpeg ', ' gif ', ' png ', ' SWF ', ' BMP ')) && function_exists (' GetImageSize ') &&! @getimagesize ($target)) {
@unlink ($target);
Upload_error (' post_attachment_ext_notallowed ', $attacharray);
}

Add: File type value encyclopedia.




123 application/vnd.lotus-1-2-3


3GP VIDEO/3GPP


AaB Application/x-authoware-bin


AAM Application/x-authoware-map


AAS Application/x-authoware-seg


Ai Application/postscript


AIF Audio/x-aiff


AIFC Audio/x-aiff


AIFF Audio/x-aiff


ALS Audio/x-alpha5


AMC Application/x-mpeg


Ani Application/octet-stream


ASC Text/plain


ASD Application/astound


ASF VIDEO/X-MS-ASF


ASN Application/astound


ASP Application/x-asap


ASX video/x-ms-asf


Au audio/basic


AVB Application/octet-stream


Avi Video/x-msvideo


AWB AUDIO/AMR-WB


Bcpio Application/x-bcpio


Bin Application/octet-stream


BLD Application/bld


Bld2 Application/bld2


BMP Application/x-ms-bmp


BPK Application/octet-stream


BZ2 APPLICATION/X-BZIP2


Cal Image/x-cals


CCN APPLICATION/X-CNC


CCO Application/x-cocoa


CDF APPLICATION/X-NETCDF


CGI magnus-internal/cgi


Chat Application/x-chat


Class Application/octet-stream


CLP Application/x-msclip


CMX APPLICATION/X-CMX


Co application/x-cult3d-object


Cod image/cis-cod


Cpio Application/x-cpio


CPT Application/mac-compactpro


CRD Application/x-mscardfile


CSH application/x-csh


CSM CHEMICAL/X-CSML


CSML CHEMICAL/X-CSML


CSS Text/css


Cur Application/octet-stream


DCM X-LML/X-EVM


DCR Application/x-director


DCX IMAGE/X-DCX


DHTML text/html


Dir application/x-director


DLL Application/octet-stream


DMG Application/octet-stream


DMS Application/octet-stream


Doc Application/msword


Dot Application/x-dot


DVI Application/x-dvi


DWF DRAWING/X-DWF


DWG Application/x-autocad


DXF Application/x-autocad


DXR Application/x-director


EBK Application/x-expandedbook


EMB Chemical/x-embl-dl-nucleotide


EMBL Chemical/x-embl-dl-nucleotide


EPS Application/postscript


Eri Image/x-eri


Es Audio/echospeech


ESL Audio/echospeech


Etc Application/x-earthtime


ETX Text/x-setext


EVM X-LML/X-EVM


Evy Application/x-envoy


EXE Application/octet-stream


Fh4 Image/x-freehand


Fh5 Image/x-freehand


FHC Image/x-freehand


Fif Image/fif


FM Application/x-maker


FPX IMAGE/X-FPX


FVI Video/isivideo


Gau Chemical/x-gaussian-input


GCA application/x-gca-compressed


GDB X-lml/x-gdb


GIF image/gif


GPS Application/x-gps


Gtar Application/x-gtar


GZ Application/x-gzip


HDF APPLICATION/X-HDF


HDM TEXT/X-HDML


HDML TEXT/X-HDML


HLP Application/winhlp


HQX application/mac-binhex40


HTM text/html


HTML text/html


HTS text/html


Ice X-conference/x-cooltalk


ICO Application/octet-stream


Ief Image/ief


IFM Image/gif


IFS Image/ifs


Imy Audio/melody


INS Application/x-net-install


IPs Application/x-ipscript


IPX Application/x-ipix


It Audio/x-mod


Itz Audio/x-mod


IVR I-WORLD/I-VRML


J2K image/j2k


Jad Text/vnd.sun.j2me.app-descriptor


Jam Application/x-jam


Jar Application/java-archive


JNLP Application/x-java-jnlp-file


JPE Image/jpeg


JPEG Image/jpeg


JPG Image/jpeg


Jpz Image/jpeg


JS Application/x-javascript


JWC APPLICATION/JWC


KJX APPLICATION/X-KJX


Lak X-lml/x-lak


Latex Application/x-latex


LCC Application/fastman


LCL Application/x-digitalloca


LCR Application/x-digitalloca


Lgh Application/lgh


LHA Application/octet-stream


LML X-lml/x-lml


Lmlpack X-lml/x-lmlpack


LSF video/x-ms-asf


LSX video/x-ms-asf


LZH Application/x-lzh


M13 Application/x-msmediaview


M14 Application/x-msmediaview


M15 Audio/x-mod


M3U Audio/x-mpegurl


M3url Audio/x-mpegurl


MA1 AUDIO/MA1


Ma2 Audio/ma2


MA3 AUDIO/MA3


MA5 AUDIO/MA5


Mans Application/x-troff-man


Map Magnus-internal/imagemap


MBD Application/mbedlet


MCT Application/x-mascot


MDB application/x-msaccess


Mdz Audio/x-mod


Me Application/x-troff-me


Mel Text/x-vmel


Mi application/x-mif


Mid Audio/midi


MIDI Audio/midi


MIF APPLICATION/X-MIF


Mil Image/x-cals


Mio Audio/x-mio


MMF application/x-skt-lbs


MNG video/x-mng


Mny Application/x-msmoney


MoC Application/x-mocha


Mocha Application/x-mocha


MoD Audio/x-mod


MOF Application/x-yumekara


MOL Chemical/x-mdl-molfile


Mop Chemical/x-mopac-input


MOV video/quicktime


Movie Video/x-sgi-movie


MP2 Audio/x-mpeg


MP3 Audio/x-mpeg


MP4 Video/mp4


MPC Application/vnd.mpohun.certificate


MPE Video/mpeg


MPEG Video/mpeg


MPG video/mpeg


MPG4 Video/mp4


MPGA Audio/mpeg


MPN application/vnd.mophun.application


MPP Application/vnd.ms-project


MPs Application/x-mapserver


MRL TEXT/X-MRML


MRM APPLICATION/X-MRM


Ms Application/x-troff-ms


MTS Application/metastream


MTX Application/metastream


MTZ Application/metastream


Mzv Application/metastream


NAR Application/zip


Nbmp image/nbmp


NC application/x-netcdf


NDB x-lml/x-ndb


Ndwn Application/ndwn


NIF application/x-nif


Nmz Application/x-scream


Nokia-op-logo Image/vnd.nok-oplogo-color


NPX APPLICATION/X-NETFPX


Nsnd audio/nsnd


NVA APPLICATION/X-NEVA1


ODA Application/oda


Oom Application/x-atlasmate-plugin


PAC Audio/x-pac


PAE Audio/x-epac


Pan Application/x-pan


PBM Image/x-portable-bitmap


PCX image/x-pcx


PDA IMAGE/X-PDA


PDB chemical/x-pdb


PDF Application/pdf


PFR APPLICATION/FONT-TDPFR


PGM Image/x-portable-graymap


PICT image/x-pict


PM Application/x-perl


PMD APPLICATION/X-PMD


PNG image/png


PNM Image/x-portable-anymap


PNZ Image/png


Pot Application/vnd.ms-powerpoint


PPM Image/x-portable-pixmap


PPS Application/vnd.ms-powerpoint


PPT Application/vnd.ms-powerpoint


PQF Application/x-cprplayer


PQI Application/cprplayer


PRC APPLICATION/X-PRC


Proxy Application/x-ns-proxy-autoconfig


PS Application/postscript


Ptlk Application/listenup


Pub Application/x-mspublisher


PVX VIDEO/X-PV-PVX


QCP Audio/vnd.qcelp


QT Video/quicktime


Qti Image/x-quicktime


Qtif Image/x-quicktime


R3T Text/vnd.rn-realtext3d


RA Audio/x-pn-realaudio


Ram Audio/x-pn-realaudio


RAR application/x-rar-compressed


RAS Image/x-cmu-raster


RDF Application/rdf+xml


RF Image/vnd.rn-realflash


RGB Image/x-rgb


Rlf Application/x-richlink


RM Audio/x-pn-realaudio


RMF AUDIO/X-RMF


RMM Audio/x-pn-realaudio


RMVB Audio/x-pn-realaudio


RNX Application/vnd.rn-realplayer


Roff Application/x-troff


RP Image/vnd.rn-realpix


RPM Audio/x-pn-realaudio-plugin


RT Text/vnd.rn-realtext


RTE X-lml/x-gps


RTF Application/rtf


RTG Application/metastream


RTX Text/richtext


RV Video/vnd.rn-realvideo


RWC Application/x-rogerwilco


S3m Audio/x-mod


s3z Audio/x-mod


SCA Application/x-supercard


SCD Application/x-msschedule


SDF Application/e-score


Sea Application/x-stuffit


SGM TEXT/X-SGML


SGML TEXT/X-SGML


SH application/x-sh


Shar Application/x-shar


sHTML magnus-internal/parsed-html


SHW application/presentations


Si6 Image/si6


Si7 image/vnd.stiwap.sis


Si9 image/vnd.lgtwap.sis


SIS Application/vnd.symbian.install


Sit application/x-stuffit


SKD Application/x-koan


SKM Application/x-koan


SKP Application/x-koan


Skt Application/x-koan


SLC Application/x-salsa


SMD AUDIO/X-SMD


SMI Application/smil


SMIL Application/smil


SMP Application/studiom


SMZ AUDIO/X-SMD


SND Audio/basic


SPC Text/x-speech


SPL Application/futuresplash


SPR Application/x-sprite


Sprite Application/x-sprite


SPT APPLICATION/X-SPT


SRC Application/x-wais-source


STK Application/hyperstudio


STM Audio/x-mod


Sv4cpio Application/x-sv4cpio


SV4CRC APPLICATION/X-SV4CRC


SVF IMAGE/VND


SVG image/svg-xml


SVH IMAGE/SVH


SVR X-world/x-svr


SWF Application/x-shockwave-flash


SWFL Application/x-shockwave-flash


T Application/x-troff


Tad Application/octet-stream


Talk Text/x-speech


Tar Application/x-tar


Taz Application/x-tar


TBP application/x-timbuktu


TBT Application/x-timbuktu


Tcl APPLICATION/X-TCL


Tex Application/x-tex


Texi Application/x-texinfo


Texinfo Application/x-texinfo


Tgz Application/x-tar


tHM Application/vnd.eri.thm


TIF Image/tiff


TIFF Image/tiff


Tki application/x-tkined


tkined application/x-tkined


TOC Application/toc


Toy Image/toy


TR Application/x-troff


TRK X-lml/x-gps


TRM Application/x-msterminal


TSI Audio/tsplayer


TSP application/dsptype


TSV Text/tab-separated-values


TSV Text/tab-separated-values


TTF Application/octet-stream


Ttz Application/t-time


TXT Text/plain


Ult Audio/x-mod


Ustar Application/x-ustar


UU Application/x-uuencode


Uue Application/x-uuencode


VCD Application/x-cdlink


VCF Text/x-vcard


VDO VIDEO/VDO


Vib Audio/vib


Viv Video/vivo


Vivo Video/vivo


VMD Application/vocaltec-media-desc


VMF Application/vocaltec-media-file


VMI Application/x-dreamcast-vms-info


VMS Application/x-dreamcast-vms


Vox Audio/voxware


VQE Audio/x-twinvq-plugin


VQF AUDIO/X-TWINVQ


VQL AUDIO/X-TWINVQ


VRE X-world/x-vream


VRML X-WORLD/X-VRML


VRT X-WORLD/X-VRT


VRW X-world/x-vream


VTS Workbook/formulaone


WAV Audio/x-wav


Wax Audio/x-ms-wax


Wbmp image/vnd.wap.wbmp


Web Application/vnd.xara


WI image/wavelet


WIS Application/x-installshield


WM VIDEO/X-MS-WM


WMA audio/x-ms-wma


WMD APPLICATION/X-MS-WMD


WMF Application/x-msmetafile


WML TEXT/VND.WAP.WML


WMLC APPLICATION/VND.WAP.WMLC


WMLS Text/vnd.wap.wmlscript


WMLSC APPLICATION/VND.WAP.WMLSCRIPTC


WMLScript Text/vnd.wap.wmlscript


WMV audio/x-ms-wmv


WMX VIDEO/X-MS-WMX


WMZ APPLICATION/X-MS-WMZ


Wpng Image/x-up-wpng


WPT X-lml/x-gps


WRI Application/x-mswrite


WRL X-WORLD/X-VRML


Wrz X-WORLD/X-VRML


WS Text/vnd.wap.wmlscript


WSC APPLICATION/VND.WAP.WMLSCRIPTC


WV Video/wavelet


WVX VIDEO/X-MS-WVX


WXL APPLICATION/X-WXL


X-gzip Application/x-gzip


Xar Application/vnd.xara


XBM Image/x-xbitmap


XDm APPLICATION/X-XDMA


XDMA APPLICATION/X-XDMA


XDW Application/vnd.fujixerox.docuworks


Xht Application/xhtml+xml


Xhtm Application/xhtml+xml


XHTML Application/xhtml+xml


XLA application/vnd.ms-excel


XLC Application/vnd.ms-excel


XLL Application/x-excel


XLM application/vnd.ms-excel


XLS application/vnd.ms-excel


XLT Application/vnd.ms-excel


XLW Application/vnd.ms-excel


XM Audio/x-mod


XML Text/xml


Xmz Audio/x-mod


XPI Application/x-xpinstall


XPM Image/x-xpixmap


Xsit Text/xml


XSL Text/xml


XUL Text/xul


XWD Image/x-xwindowdump


XYZ chemical/x-pdb


YZ1 APPLICATION/X-YZ1


Z application/x-compress


Zac Application/x-zaurus-zac


Zip Application/zip

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.