您好,欢迎来到三六零分类信息网!老站,搜索引擎当天收录,欢迎发信息

php判断上传文件文件类型的安全方法

2025/4/3 2:16:04发布61次查看
在使用 php 进行文件的上传和存储时,很多人都会给文件进行重名命并保存到可写文件夹下,然后我们在其中一个失误的地方便是采用上传文件的扩展名作为判断文件类型的依据。
这样做其实与后门大开无异,举一个简单的例子,通过扩展名判断一般是字符串的截取判断,或者是使用$_file数组判断,然后如果用户上传的文件名为 image.php.png, image.png.php, image.php%****.png 之类的话,判断就会出错。
另外,$_files['type']可能被篡改。
下面是我判断文件名的方法:
读取文件头四个字节作为判断。         
下面直接上代码
我实现的是仅支持word和pdf文件,且文件大小小于512kb:
$tmpname = $_files ['userfile'] ['tmp_name']; if(is_uploaded_file($tmpname)) { $mimetype = detectmime($tmpname); $tuozhanming = getfileext($filename, $mimetype); if($tuozhanming == type_error){ echo '仅支持word和pdf文件,且文件大小小于512kb:请重试'; exit(); } }else{ $_files ['userfile'] ['error'] = 6; } if ($_files ['userfile'] ['error'] > 0) { echo 'problem: '; switch ($_files ['userfile'] ['error']) { case 1 : echo '上传文件过大:请重试'; break; case 2 : echo '上传文件过大:请重试'; break; case 3 : echo '文件上传丢失:请重试'; break; case 4 : echo '无文件被上传:请重试'; break; case 6 : echo '仅支持word和pdf文件,且文件大小小于512kb:请重试'; break; case 7 : echo '上传文件存储失败:请重试'; break; } exit (); } //判断文件类型 //上传文件 $_files ['userfile'] ['name'] = time () . . . $tuozhanming; $upfile = '../uploads/' . $_files ['userfile'] ['name']; if ( !move_uploaded_file ( $_files ['userfile'] ['tmp_name'], $upfile )) { echo 'problem: 文件移动失败'; exit (); } }function detectmime($filename) { $file = fopen ( $filename, rb ); $finfo = finfo_open ( fileinfo_mime ); if (! $finfo) { // 直接读取文件的前4个字节,根据硬编码判断 $file = fopen ( $filename, rb ); $bin = fread ( $file, 4 ); //只读文件头4字节 fclose ( $file ); $strinfo = @unpack ( c4chars, $bin ); //dechex() 函数把十进制转换为十六进制。 $typecode = dechex ( $strinfo ['chars1'] ) . dechex ( $strinfo ['chars2'] ) . dechex ( $strinfo ['chars3'] ) . dechex ( $strinfo ['chars4'] ); $type = ''; switch ($typecode) //硬编码值查表 { 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;}
该用户其它信息

VIP推荐

免费发布信息,免费发布B2B信息网站平台 - 三六零分类信息网 沪ICP备09012988号-2
企业名录 Product