Files
4WDCSA.co.za/src/processors/blog/submit_blog.php
twotalesanimation a66382661d Fixed some bugs
2025-12-13 19:25:47 +02:00

84 lines
3.0 KiB
PHP

<?php
$rootPath = dirname(dirname(dirname(__DIR__)));
require_once($rootPath . "/src/config/env.php");
require_once($rootPath . "/src/config/connection.php");
require_once($rootPath . "/src/config/functions.php");
session_start();
if (!isset($_SESSION['user_id'])) {
die("Login required");
}
$title = $_POST['title'];
$category = $_POST['category'];
$description = $_POST['description'];
$content = $_POST['content'];
$user_id = $_SESSION['user_id'];
$date = date('Y-m-d');
$article_id = $_POST['article_id'] ?? null;
$image = null;
// Handle cover image upload if provided
if (isset($_FILES['cover_image']) && $_FILES['cover_image']['error'] === UPLOAD_ERR_OK) {
// For new blogs, we'll use the blog_id after insert, for now use temp folder
// Update: For editing, use article_id; for new blogs, we'll need to handle this after insert
$folder_id = $article_id ?? 'temp_' . uniqid();
$upload_dir = $rootPath . '/uploads/blogs/' . $folder_id . '/';
// Create directory if it doesn't exist
if (!file_exists($upload_dir)) {
mkdir($upload_dir, 0777, true);
}
// Validate and process the file
$file_result = validateFileUpload($_FILES['cover_image'], 'profile_picture');
if ($file_result !== false) {
// Use fixed filename "cover" to avoid duplicates
$extension = $file_result['extension'];
$filename = "cover." . $extension;
// Delete old cover if it exists with different extension
array_map('unlink', glob($upload_dir . "cover.*"));
$upload_path = $upload_dir . $filename;
if (move_uploaded_file($_FILES['cover_image']['tmp_name'], $upload_path)) {
// Store relative path for database
$image = '/uploads/blogs/' . $folder_id . '/' . $filename;
}
}
}
// If updating an existing blog, get the existing image if no new one was uploaded
if ($article_id && !$image) {
$check_stmt = $conn->prepare("SELECT image FROM blogs WHERE blog_id = ?");
$check_stmt->bind_param("i", $article_id);
$check_stmt->execute();
$result = $check_stmt->get_result();
if ($result->num_rows > 0) {
$row = $result->fetch_assoc();
$image = $row['image'];
}
$check_stmt->close();
}
// Check if this is an update or insert
if ($article_id) {
// Update existing blog
$stmt = $conn->prepare("UPDATE blogs SET title = ?, content = ?, description = ?, category = ?" . ($image ? ", image = ?" : "") . " WHERE blog_id = ?");
if ($image) {
$stmt->bind_param("sssssi", $title, $content, $description, $category, $image, $article_id);
} else {
$stmt->bind_param("ssssi", $title, $content, $description, $category, $article_id);
}
} else {
// Insert new blog
$stmt = $conn->prepare("INSERT INTO blogs (author, title, content, description, category, date, image) VALUES (?, ?, ?, ?, ?, ?, ?)");
$stmt->bind_param("issssss", $user_id, $title, $content, $description, $category, $date, $image);
}
$stmt->execute();
$stmt->close();
header("Location: blog.php");