PHP image Upload, if you do not make any judgment, any file such as Rar,zip,php,java file name change, a suffix can be uploaded as a picture of the server, often cause great harm!
Tools/Materials
- Php
- Apache/nginx/iis
- phpstorm/netbeans/notepad++/EditPlus
Method/Step
- 1
The first method: if it is simply to determine whether it is a picture format, I use the GetImageSize method function Checkisimage ($filename) {$alltypes = '. Gif|. Jpeg|. Png|. BMP ';//define the type of picture to check if (file_exists ($filename)) {$result = getimagesize ($filename); $ext = Image_type_to_extension ($result ']); Return Stripos ($alltypes, $ext); }else{return false; }}
- 2
The second method is more powerful, can judge multiple formats function Getreailfiletype ($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 '; case 7784: $fileType = ' midi '; Break case 8297: $fileType = ' rar '; Break case 255216: $fileType = ' jpg '; case 7173: $fileType = ' gif '; case 6677: $fileType = ' bmp '; case 13780: $fileType = ' png '; default: $fileType = ' unknown '; } return $fileType;}
- 3
The third method:
The PHP GD class library function provides a exif_imagetype () function to read the 1th byte of an image and to check the signature of the picture. If the format is not correct, it returns false. In fact, this method and the first method have the same kind of wonderful. But because this is a library function, efficiency is much higher than the first method.
This function is very simple to use, pass in the path, and then determine if it is equal to a constant, such as the imagetype_gif in GIF format
thinkphp useful to this judgment www\thinkphp\library\think\validate.php
- 4
Fourth method: PHP Redraw
A method of low efficiency, but it is also a way of thinking: the transmission of files, no matter what files are resource type in the picture, if it is a picture, can be restored. If it is not a picture, the painting does not come out, and the inside of the dangerous code is not.
For details, see:
- 5 Summary: I have seen on the internet that someone said: believe that people who know PHP have used the XX function. I opened it up to a function that uses a suffix to determine the type of upload. Students do similar functions when you must uncover the performance to see the essence, otherwise disguised pictures after uploading, will cause great security risks to the server
PHP image upload detection is a real image format