更新图片上传可能的漏洞

This commit is contained in:
技术老胡
2025-05-09 09:06:48 +08:00
parent e524424628
commit 98c90dffcf

View File

@@ -7,6 +7,7 @@ namespace app\controller\api;
use app\BaseController; use app\BaseController;
use app\model\PayAccount; use app\model\PayAccount;
use app\model\PayChannel; use app\model\PayChannel;
use \think\facade\Log;
class PayManageController extends BaseController class PayManageController extends BaseController
{ {
@@ -125,23 +126,48 @@ class PayManageController extends BaseController
// 上传二维码图片 // 上传二维码图片
public function uploadQrcode() public function uploadQrcode()
{ {
try {
// 获取上传的文件
$img = $this->request->file('codeimg'); $img = $this->request->file('codeimg');
if (!$img) { if (!$img) {
return json(backMsg(1, '请选择要上传的文件')); return json(backMsg(1, '请选择要上传的文件'));
} }
// 验证文件类型
// 验证文件大小,防止大文件攻击
$maxSize = 2 * 1024 * 1024; // 2MB
if ($img->getSize() > $maxSize) {
return json(backMsg(1, '文件大小不能超过 2MB'));
}
// 验证文件类型,防止恶意文件上传
$allowedTypes = ['image/png', 'image/jpeg', 'image/gif']; $allowedTypes = ['image/png', 'image/jpeg', 'image/gif'];
$fileMimeType = $img->getMime(); $fileMimeType = $img->getMime();
if (!in_array($fileMimeType, $allowedTypes)) { if (!in_array($fileMimeType, $allowedTypes)) {
return json(backMsg(1, '只允许上传PNG、JPEGGIF格式的图片')); return json(backMsg(1, '只允许上传 PNG、JPEGGIF 格式的图片'));
} }
// 生成唯一文件名
// 二次验证文件类型,通过文件内容判断
$finfo = finfo_open(FILEINFO_MIME_TYPE);
$realMimeType = finfo_file($finfo, $img->getRealPath());
finfo_close($finfo);
if (!in_array($realMimeType, $allowedTypes)) {
return json(backMsg(1, '文件类型验证失败,请上传有效的图片文件'));
}
// 生成唯一文件名,避免文件名冲突
$filename = 'img_' . time() . '_' . uniqid() . '.' . $img->getOriginalExtension(); $filename = 'img_' . time() . '_' . uniqid() . '.' . $img->getOriginalExtension();
// 过滤文件名,防止路径遍历攻击
$filename = preg_replace('/[^a-zA-Z0-9_\-\.]/', '', $filename);
// 设置文件保存路径 // 设置文件保存路径
$path = public_path() . '/files/qrcode/'; $path = public_path() . '/files/qrcode/';
if (!is_dir($path)) { if (!is_dir($path)) {
mkdir($path, 0755, true); if (!mkdir($path, 0755, true)) {
return json(backMsg(1, '创建目录失败'));
} }
}
// 移动文件到指定目录 // 移动文件到指定目录
$info = $img->move($path, $filename); $info = $img->move($path, $filename);
if ($info) { if ($info) {
@@ -150,6 +176,10 @@ class PayManageController extends BaseController
} else { } else {
return json(backMsg(1, '上传失败')); return json(backMsg(1, '上传失败'));
} }
} catch (\Exception $e) {
Log::error('上传过程中出现异常: ' . $e->getMessage());
return json(backMsg(1, '上传过程中出现异常,请稍后重试'));
}
} }
// 获取账号交易流水 // 获取账号交易流水
public function getAccountTrade() public function getAccountTrade()