上传文件至 /

Signed-off-by: admin <15630053159@163.com>
This commit is contained in:
2026-11-27 15:40:59 +08:00
commit f8d6ddd016
5 changed files with 546 additions and 0 deletions

71
up_pic.php Normal file
View File

@@ -0,0 +1,71 @@
<?php
require_once __DIR__ . '/includes/auth.php';
require_once __DIR__ . '/includes/upload_guard.php';
header('Content-Type: application/json; charset=utf-8');
function reply($arr, $code = 200)
{
http_response_code($code);
echo json_encode($arr, JSON_UNESCAPED_UNICODE);
exit;
}
$user = current_user($conn);
if (!$user) {
reply(['success' => false, 'message' => '登录已失效,请重新登录。'], 401);
}
if ($_SERVER['REQUEST_METHOD'] !== 'POST' || !csrf_ok()) {
reply(['success' => false, 'message' => '请求校验失败,请刷新页面重试。'], 400);
}
$MAX_BYTES = 8 * 1024 * 1024; // 原始文件上限 8MB
$MAX_SIDE = 600; // 保存后的最长边
// 三重校验:真实图片 → GD 解码 → 重编码(剥离夹带脚本与 EXIF),细节见 upload_guard.php
$res = decode_uploaded_image($_FILES['image'] ?? null, $MAX_BYTES);
if (!$res['ok']) {
reply(['success' => false, 'message' => $res['message']]);
}
$dst = gd_fit($res['src'], $MAX_SIDE);
$newFilename = safe_file_base($_FILES['image']['name']) . '_' . bin2hex(random_bytes(6)) . '.png';
$absPath = __DIR__ . '/uploads/' . $newFilename;
if (!imagepng($dst, $absPath, 6)) {
imagedestroy($dst);
reply(['success' => false, 'message' => '图片保存失败,请稍后再试。'], 500);
}
imagedestroy($dst);
// 原子扣分 + 写库,扣分失败就删文件
$update = $conn->prepare("UPDATE photo_users SET points = points - 1 WHERE user_id = ? AND points > 0");
$update->bind_param("i", $user['user_id']);
$update->execute();
if ($update->affected_rows === 0) {
$update->close();
@unlink($absPath);
reply(['success' => false, 'message' => '积分不足,无法上传。']);
}
$update->close();
$relPath = 'uploads/' . $newFilename;
$ins = $conn->prepare("INSERT INTO images (user_id, image_path) VALUES (?, ?)");
$ins->bind_param("is", $user['user_id'], $relPath);
if (!$ins->execute()) {
$ins->close();
@unlink($absPath);
$refund = $conn->prepare("UPDATE photo_users SET points = points + 1 WHERE user_id = ?");
$refund->bind_param("i", $user['user_id']);
$refund->execute();
$refund->close();
reply(['success' => false, 'message' => '图片信息写入失败。'], 500);
}
$ins->close();
reply([
'success' => true,
'message' => '上传成功',
'image_id' => $conn->insert_id,
'new_filename' => $newFilename,
'points' => $user['points'] - 1,
]);