// Enable error reporting for debugging ini_set('display_errors', 1); ini_set('display_startup_errors', 1); error_reporting(E_ALL); session_start(); // CORS Headers (Allow requests from Angular frontend) header("Access-Control-Allow-Origin: http://localhost:4200"); header("Access-Control-Allow-Methods: POST, OPTIONS"); header("Access-Control-Allow-Headers: Content-Type, Authorization"); header("Access-Control-Allow-Credentials: true"); // Handle Preflight Request if ($_SERVER['REQUEST_METHOD'] === 'OPTIONS') { http_response_code(204); exit; } // Include database connection include 'db.php'; // Logging $log_file = "log.txt"; file_put_contents($log_file, "PHP Script Started\n", FILE_APPEND); // Read JSON input $rawInput = file_get_contents('php://input'); file_put_contents($log_file, "Received RAW Data: " . $rawInput . "\n", FILE_APPEND); // Try decoding JSON data $data = json_decode($rawInput, true); if ($data === null) { file_put_contents($log_file, "No JSON data found, checking POST...\n", FILE_APPEND); } // Extract user ID and title from both JSON and form-data $user_id = $data['user_id'] ?? $_POST['user_id'] ?? null; $title = $data['story_title'] ?? $_POST['story_title'] ?? null; // Log received data file_put_contents($log_file, "Extracted User ID: $user_id, Title: $title\n", FILE_APPEND); // Validate required fields if (empty($user_id) || empty($title)) { file_put_contents($log_file, "ERROR: Missing User ID or Title\n", FILE_APPEND); echo json_encode(['status' => 'error', 'message' => 'User ID and Title are required']); exit; } try { // Sanitize input (prevent XSS) $sanitized_title = htmlspecialchars($title, ENT_QUOTES, 'UTF-8'); // Prepare SQL statement $stmt = $pdo->prepare("INSERT INTO storytitle (user_id, title) VALUES (:user_id, :title)"); $stmt->bindParam(':user_id', $user_id, PDO::PARAM_INT); $stmt->bindParam(':title', $sanitized_title, PDO::PARAM_STR); // Execute query $stmt->execute(); // Log success file_put_contents($log_file, "SUCCESS: Story Added\n", FILE_APPEND); // Success response echo json_encode(['status' => 'success', 'message' => 'Story title added successfully']); } catch (PDOException $e) { // Log error file_put_contents($log_file, "DB ERROR: " . $e->getMessage() . "\n", FILE_APPEND); // Error response echo json_encode(['status' => 'error', 'message' => 'Query failed: ' . $e->getMessage()]); }