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" => "不支持的请求方法"]);