bash
function getReailFileType($filename){
$file = fopen($filename, "rb");
$bin = fread($file, 2); //只读2字节
fclose($file);
$strInfo = @unpack("C2chars", $bin);
$typeCode = intval($strInfo['chars1'].$strInfo['chars2']);
$fileType = '';
switch($typeCode){
case 255216:
$fileType = 'jpg';
break;
case 13780:
$fileType = 'png';
break;
case 7173:
$fileType = 'gif';
break;
default:
$fileType = 'unknown';
}
return $fileType;
}
$is_upload = false;
$msg = null;
if(isset($_POST['submit'])){
$temp_file = $_FILES['upload_file']['tmp_name'];
$file_type = getReailFileType($temp_file);
if($file_type == 'unknown'){
$msg = "文件未知,上传失败!";
}else{
$img_path = UPLOAD_PATH."/".rand(10, 99).date("YmdHis").".".$file_type;
if(move_uploaded_file($temp_file,$img_path)){
$is_upload = true;
} else {
$msg = "上传出错!";
}
}
}
该代码定义了一个 getReailFileType
函数,其工作原理是打开用户上传的临时文件,以二进制模式读取前2个字节。随后,使用 unpack
函数将这两个字节解析为两个无符号字符(C2chars
),并将它们的十进制值拼接成一个整数 $typeCode
。通过一个 switch
语句匹配该整数,从而判断文件类型:255216
对应 JPEG(字节为 FF D8
),13780
对应 PNG(字节为 89 50
),7173
对应 GIF(字节为 47 49
)。若类型匹配,则使用该类型扩展名重命名文件并移动到指定上传目录;若为 unknown
,则上传被拒绝。
在主流程中,代码通过 isset($_POST['submit'])
检测表单提交,获取上传文件的临时路径,并调用 getReailFileType
函数检测真实文件类型。这是一种基于文件内容本身的初步验证方法,比单纯检查文件名扩展更为可靠。
1.准备「图马」任选一张小图 pic.jpg
,命令行拼接:

linux系统命令:

用文件包含漏洞执行
靶场会给出一个 include.php
(或 ?file=
参数),把图片路径传进去:
http://localhost:7298/upload-labs/include.php?file=upload/xx20251007.jpg
该页面会把图片内容当成 PHP 解析,木马生效。
再通过蚁剑连接
