
本文介绍如何在 php 中将用户通过 base64 上传并保存到本地目录(如 support_data/)的图片,立即通过 telegram bot api 发送至指定聊天(chat_id),包含完整代码、关键配置说明及安全注意事项。
本文介绍如何在 php 中将用户通过 base64 上传并保存到本地目录(如 support_data/)的图片,立即通过 telegram bot api 发送至指定聊天(chat_id),包含完整代码、关键配置说明及安全注意事项。
要实现“前端上传图片 → 后端解码保存 → 自动发送至 Telegram”,需完成三个核心步骤:Base64 图片解析与本地存储、Telegram Bot API 身份认证、以及使用 cURL 以 multipart/form-data 方式上传文件。以下为完整、可运行的优化版实现:
✅ 完整 PHP 示例代码(含错误处理与安全建议)
<?php // 配置项:请务必替换为你的实际值
$bot_token = 'YOUR_BOT_TOKEN_HERE'; // 如:123456789:ABC-DEF123xyz...
$chat_id = 'YOUR_CHAT_ID_OR_GROUP_ID'; // 可为用户 ID(正数)、群组 ID(负数,如 -1001234567890)
$folderPath = "support_DATA/";
if (!is_dir($folderPath)) {
mkdir($folderPath, 0755, true);
}
// 获取 Base64 图片数据(来自 hidden input)
$img = $_POST['image'] ?? '';
if (empty($img) || !str_starts_with($img, 'data:image/')) {
http_response_code(400);
die("错误:未收到有效的 Base64 图片数据");
}
// 解析 Base64 数据
$image_parts = explode(';base64,', $img);
if (count($image_parts) !== 2) {
http_response_code(400);
die("错误:Base64 格式不合法");
}
$image_type_aux = explode('image/', $image_parts[0]);
$image_type = $image_parts[0] === '' ? 'png' : ($image_type_aux[1] ?? 'png');
$image_type = strtolower($image_type);
// 允许的安全类型(防御性过滤)
$allowed_types = ['png', 'jpg', 'jpeg', 'gif'];
if (!in_array($image_type, $allowed_types)) {
http_response_code(400);
die("错误:仅支持 PNG/JPG/GIF 格式");
}
$image_base64 = base64_decode($image_parts[1]);
if ($image_base64 === false) {
http_response_code(400);
die("错误:Base64 解码失败");
}
$fileName = uniqid('tg_', true) . '.' . $image_type;
$file = $folderPath . $fileName;
if (file_put_contents($file, $image_base64) === false) {
http_response_code(500);
die("错误:无法写入文件");
}
// 构建 Telegram API 请求
$bot_url = "https://api.telegram.org/bot{$bot_token}/";
$url = $bot_url . "sendPhoto";
$post_fields = [
'chat_id' => $chat_id,
'photo' => new CURLFile($file, "image/{$image_type}", $fileName),
];
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $post_fields);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); // 生产环境建议设为 true 并配置 CA 证书
$response = curl_exec($ch);
$http_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);
// 清理:可选 —— 成功后删除本地文件(避免磁盘占用)
if ($http_code === 200) {
unlink($file);
}
// 返回结果(便于前端调试)
if ($http_code === 200) {
echo json_encode(['status' => 'success', 'file' => $fileName, 'telegram_response' => json_decode($response, true)]);
} else {
error_log("Telegram API Error [{$http_code}]: " . print_r(json_decode($response, true), true));
echo json_encode(['status' => 'error', 'message' => '发送失败,请检查 bot_token 和 chat_id']);
}
?>
⚠️ 关键注意事项
- Bot Token 与 Chat ID 安全:$bot_token 和 $chat_id 不得硬编码在公开代码中;推荐通过环境变量(如 .env + getenv())或配置文件(权限设为 600)管理。
- CURLFile 兼容性:要求 PHP ≥ 5.5.0;若使用旧版本,需改用 @/full/path/to/file(已弃用,不推荐)。
- 文件权限与路径安全:确保 support_DATA/ 目录可写且不在 Web 可访问路径下(如置于 public_html 外),防止任意文件读取。
- Base64 输入验证:必须校验前缀、解码有效性及 MIME 类型,避免恶意 payload。
- Telegram 限制:单图最大 10MB;超大图建议压缩或转为文档发送(sendDocument)。
✅ 总结
该方案将 Base64 图片落地为物理文件后,利用 CURLFile 实现零内存加载的流式上传,兼顾稳定性与兼容性。配合基础校验与清理逻辑,即可构建健壮的 Telegram 图片自动通知服务——适用于客服工单、表单反馈、监控告警等场景。
php免费学习视频:立即使用
踏上前端学习之旅,开启通往精通之路!从前端基础到项目实战,循序渐进,一步一个脚印,迈向巅峰!











