task-report/api.php
2025-04-14 00:33:31 +08:00

141 lines
4.9 KiB
PHP
Raw Permalink Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

<?php
// 设置错误报告
ini_set('display_errors', 1);
error_reporting(E_ALL);
// 允许跨域请求
header("Access-Control-Allow-Origin: *");
header("Access-Control-Allow-Methods: POST, GET, OPTIONS");
header("Access-Control-Allow-Headers: Content-Type");
header("Content-Type: application/json; charset=UTF-8");
// 处理OPTIONS请求预检请求
if ($_SERVER['REQUEST_METHOD'] === 'OPTIONS') {
http_response_code(200);
exit;
}
// 数据库连接信息
$db_host = '192.168.2.4';
$db_port = 3307;
$db_name = 'task_reporter';
$db_user = 'task_reporter';
$db_pass = 'Pass12349ers!';
// 创建数据库连接
try {
$pdo = new PDO("mysql:host=$db_host;port=$db_port;dbname=$db_name", $db_user, $db_pass);
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$pdo->exec("SET NAMES utf8");
} catch (PDOException $e) {
echo json_encode(["error" => "数据库连接失败: " . $e->getMessage()]);
exit;
}
// 记录请求到日志文件
function log_request($message) {
$log_file = __DIR__ . '/api_log.txt';
$timestamp = date('Y-m-d H:i:s');
$log_message = "[$timestamp] $message\n";
file_put_contents($log_file, $log_message, FILE_APPEND);
}
// 处理添加任务的POST请求
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
try {
log_request("收到POST请求");
$raw_data = file_get_contents('php://input');
log_request("原始数据: $raw_data");
$data = json_decode($raw_data, true);
if (!$data) {
throw new Exception("无效的JSON数据: " . json_last_error_msg());
}
log_request("解析后的数据: " . print_r($data, true));
// 验证必要字段
$required_fields = ['username', 'tool_name', 'task_name', 'time_saved', 'time_cost'];
foreach ($required_fields as $field) {
if (!isset($data[$field]) || (is_string($data[$field]) && trim($data[$field]) === '')) {
throw new Exception("缺少必要字段: $field");
}
}
// 如果没有提供时间戳,使用当前时间
if (!isset($data['timestamp']) || empty($data['timestamp'])) {
$data['timestamp'] = date('Y-m-d H:i:s');
log_request("使用当前时间作为时间戳: {$data['timestamp']}");
}
// 确保时间戳格式正确
if (strpos($data['timestamp'], 'T') !== false) {
$parts = explode(".", $data['timestamp']);
$data['timestamp'] = str_replace("T", " ", $parts[0]);
log_request("转换ISO时间戳格式: {$data['timestamp']}");
}
// 准备SQL语句
$stmt = $pdo->prepare("INSERT INTO task (username, tool_name, task_name, time_saved, time_cost, timestamp)
VALUES (:username, :tool_name, :task_name, :time_saved, :time_cost, :timestamp)");
// 绑定参数
$stmt->bindParam(':username', $data['username']);
$stmt->bindParam(':tool_name', $data['tool_name']);
$stmt->bindParam(':task_name', $data['task_name']);
$stmt->bindParam(':time_saved', $data['time_saved']);
$stmt->bindParam(':time_cost', $data['time_cost']);
$stmt->bindParam(':timestamp', $data['timestamp']);
log_request("准备执行SQL插入");
// 执行SQL
$result = $stmt->execute();
if ($result) {
$last_id = $pdo->lastInsertId();
log_request("数据成功插入ID: $last_id");
echo json_encode([
"success" => true,
"message" => "{$data['timestamp']} {$data['tool_name']}-{$data['task_name']} reported successfully!",
"id" => $last_id
]);
} else {
log_request("数据插入失败");
throw new Exception("数据插入失败");
}
} catch (Exception $e) {
log_request("错误: " . $e->getMessage());
http_response_code(400);
echo json_encode([
"success" => false,
"error" => $e->getMessage()
]);
}
exit;
}
// 处理简单的GET请求用于测试API是否正常工作
if ($_SERVER['REQUEST_METHOD'] === 'GET') {
echo json_encode([
"status" => "API正常工作",
"message" => "使用POST请求提交任务数据",
"example" => [
"username" => "用户名",
"tool_name" => "工具名称",
"task_name" => "任务名称",
"time_saved" => "节省时间(小时)",
"time_cost" => "花费时间(小时)",
"timestamp" => "可选格式YYYY-MM-DD HH:MM:SS"
],
"contact" => "jeffreytsai1004@gmail.com"
]);
exit;
}
// 如果不是GET或POST请求返回错误
http_response_code(405);
echo json_encode(["error" => "不支持的请求方法"]);