Pārlūkot izejas kodu

Upload files to 'api'

Parv Ashwani 10 mēneši atpakaļ
vecāks
revīzija
9b2a558cc6
3 mainītis faili ar 47 papildinājumiem un 0 dzēšanām
  1. 9 0
      api/fetch_messages.php
  2. 4 0
      api/logout.php
  3. 34 0
      api/send_message.php

+ 9 - 0
api/fetch_messages.php

@@ -0,0 +1,9 @@
+<?php
+header('Content-Type: application/json');
+
+$pdo = new PDO('mysql:host=sql101.infinityfree.com;dbname=if0_39567875_nex', 'if0_39567875', 'PIvOR9WViHm');  // Update
+
+$stmt = $pdo->query("SELECT m.*, u.username FROM messages m JOIN users u ON m.user_id = u.id ORDER BY m.created_at ASC");
+$messages = $stmt->fetchAll(PDO::FETCH_ASSOC);
+
+echo json_encode($messages);

+ 4 - 0
api/logout.php

@@ -0,0 +1,4 @@
+<?php
+session_start();
+session_destroy();
+header('Location: ../register.php');

+ 34 - 0
api/send_message.php

@@ -0,0 +1,34 @@
+<?php
+session_start();
+header('Content-Type: application/json');
+
+if (!isset($_SESSION['user_id'])) {
+    echo json_encode(['success' => false, 'error' => 'Not logged in']);
+    exit;
+}
+
+$pdo = new PDO('mysql:host=sql101.infinityfree.com;dbname=if0_39567875_nex', 'if0_39567875', 'PIvOR9WViHm');  // Update
+
+$message = htmlspecialchars($_POST['message'] ?? '');
+$attachmentPath = '';
+$isImage = 0;
+
+if (isset($_FILES['attachment']) && $_FILES['attachment']['error'] === 0) {
+    $fileName = basename($_FILES['attachment']['name']);
+    $targetPath = '../uploads/' . $fileName;
+    if (move_uploaded_file($_FILES['attachment']['tmp_name'], $targetPath)) {
+        $attachmentPath = 'uploads/' . $fileName;
+        $mime = mime_content_type($targetPath);
+        if (strpos($mime, 'image/') === 0) {
+            $isImage = 1;
+        }
+    } else {
+        echo json_encode(['success' => false, 'error' => 'Upload failed']);
+        exit;
+    }
+}
+
+$stmt = $pdo->prepare("INSERT INTO messages (user_id, message_text, attachment_path, is_image) VALUES (?, ?, ?, ?)");
+$success = $stmt->execute([$_SESSION['user_id'], $message, $attachmentPath, $isImage]);
+
+echo json_encode(['success' => $success]);