index.php 2.52 KB
<?php
// File: index.php

// Import kelas CMS dan Post
require_once 'classes/Post.php';

// Mulai session untuk menyimpan post sementara
session_start();

// Inisialisasi array post jika belum ada
if (!isset($_SESSION['posts'])) {
    $_SESSION['posts'] = [];
}

// Jika form disubmit, tambahkan post ke session
if ($_SERVER['REQUEST_METHOD'] == 'POST' && isset($_POST['action']) && $_POST['action'] === 'add_post') {
    $title = $_POST['title'];
    $author = $_POST['author'];
    $content = $_POST['content'];
    $category = $_POST['category'];

    // Buat objek Post baru
    $newPost = new Post($title, $author, $content, $category);

    // Simpan post ke session
    $_SESSION['posts'][] = $newPost;
}

// Jika permintaan untuk menghapus post diterima
if (isset($_POST['action']) && $_POST['action'] === 'delete_post' && isset($_POST['post_index'])) {
    $postIndex = $_POST['post_index'];
    // Hapus post berdasarkan index
    array_splice($_SESSION['posts'], $postIndex, 1);
}
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Simple CMS - Add Post</title>
    <link rel="stylesheet" href="style.css">
</head>
<body>

<h1>Create a New Post</h1>

<!-- Form untuk membuat post baru -->
<form action="" method="POST" class="post-form">
    <input type="hidden" name="action" value="add_post">
    <label for="title">Title:</label>
    <input type="text" id="title" name="title" required><br>

    <label for="author">Author:</label>
    <input type="text" id="author" name="author" required><br>

    <label for="content">Content:</label>
    <textarea id="content" name="content" required></textarea><br>

    <label for="category">Category:</label>
    <input type="text" id="category" name="category" required><br>

    <button type="submit">Submit Post</button>
</form>

<hr>

<!-- Tampilkan semua post yang sudah dibuat -->
<h2>All Posts:</h2>

<?php
if (count($_SESSION['posts']) > 0) {
    foreach ($_SESSION['posts'] as $index => $post) {
        echo "<div class='post'><h2>Post " . ($index + 1) . ":</h2>";
        $post->displayPost();

        // Form untuk menghapus post
        echo "
        <form action='' method='POST'>
            <input type='hidden' name='action' value='delete_post'>
            <input type='hidden' name='post_index' value='$index'>
            <button type='submit' class='delete-button'>Delete</button>
        </form>";

        echo "</div>";
    }
} else {
    echo "<p>No posts available.</p>";
}
?>

</body>
</html>