/
codxplr
/
simple-php-blog
Обзор
Документация
Войти
/
codxplr
/
simple-php-blog
Код
Запросы
0
Задачи
Вики
Пакеты
0
Релизы
0
CI/CD
Аналитика
Безопасность
master
article.php
140 строк
5 KB
codxplr
Create: article.php, config.php, editor.php, index.php, init.php, login.php, logout.php, sql_dump.sql, toggle_publish.php
08 авг 2026, 21:23
Верифицирован
08 авг 2026, 21:23
1113d72
Код
Авторство
О чём код?
<?php require 'init.php'; // Обработка формы комментария if ($_SERVER['REQUEST_METHOD'] === 'POST') { check_csrf(); $post_slug = $_GET['slug'] ?? ''; $stmt = $pdo->prepare("SELECT id FROM posts WHERE slug = ? AND published = 1 LIMIT 1"); $stmt->execute([$post_slug]); $post = $stmt->fetch(); if (!$post) { die('Статья не найдена.'); } // Валидация полей $author_name = trim($_POST['author_name'] ?? ''); $author_email = trim($_POST['author_email'] ?? ''); $content = trim($_POST['content'] ?? ''); $is_anonymous = isset($_POST['anonymous']) && $_POST['anonymous'] === 'on'; $errors = []; if ($is_anonymous) { if (empty($content)) { $errors[] = 'Текст комментария не может быть пустым.'; } } else { if (empty($author_name)) { $errors[] = 'Введите имя.'; } if (!filter_var($author_email, FILTER_VALIDATE_EMAIL)) { $errors[] = 'Введите корректный email.'; } if (empty($content)) { $errors[] = 'Текст комментария не может быть пустым.'; } if (strlen($content) > 2000) { $errors[] = 'Комментарий слишком длинный.'; } } if (empty($errors)) { $stmt = $pdo->prepare("INSERT INTO comments (post_id, author_name, author_email, content, is_anonymous, user_id) VALUES (?, ?, ?, ?, ?, NULL)"); // Для анонимных пользователей записываем только текст, поля имени затираем $stmt->execute([ $post['id'], $is_anonymous ? null : e($author_name), $is_anonymous ? null : e($author_email), nl2br(e($content)), $is_anonymous ? 1 : 0 ]); redirect("article.php?slug=" . urlencode($post_slug)); } } // Просмотр статьи $slug = $_GET['slug'] ?? ''; $stmt = $pdo->prepare("SELECT * FROM posts WHERE slug = ? AND published = 1 LIMIT 1"); $stmt->execute([$slug]); $post = $stmt->fetch(); if (!$post) { http_response_code(404); die('Страница не найдена.'); } // Получаем комментарии $commentStmt = $pdo->prepare("SELECT * FROM comments WHERE post_id = ? ORDER BY created_at ASC"); $commentStmt->execute([$post['id']]); $comments = $commentStmt->fetchAll(); ?> <!DOCTYPE html> <html lang="ru"> <head> <meta charset="UTF-8"> <title><?= e($post['title']) ?> — Мой блог</title> <link rel="stylesheet" href="assets/style.css"> </head> <body> <header><h1><a href="index.php">Мой простой блог</a></h1></header> <article class="post-card"> <?php if($post['image_path']): ?> <img src="<?= e($post['image_path']) ?>" alt="<?= e($post['title']) ?>"> <?php endif; ?> <h2><?= e($post['title']) ?></h2> <div class="post-meta"><?= date('d.m.Y H:i', strtotime($post['created_at'])) ?></div> <div><?= $post['content'] ?></div> </article> <hr style="margin: 40px 0;"> <h3>Комментарии (<?= count($comments) ?>)</h3> <?php foreach($comments as $c): ?> <div class="comment"> <strong><?= $c['is_anonymous'] ? 'Аноним' : e($c['author_name']) ?></strong> <span style="color:#666; font-size:0.9em;">— <?= date('d.m.Y H:i', strtotime($c['created_at'])) ?></span> <p><?= $c['content'] ?></p> </div> <?php endforeach; ?> <h3>Добавить комментарий</h3> <?php if(!empty($errors)): ?> <div style="background:#f8d7da; color:#721c24; padding:10px; border-radius:4px; margin-bottom:15px;"> <?php foreach($errors as $err): echo "<p>" . e($err) . "</p>"; endforeach; ?> </div> <?php endif; ?> <form method="post"> <input type="hidden" name="csrf_token" value="<?= e(csrf_token()) ?>"> <label> <input type="checkbox" name="anonymous" onchange="toggleAnon(this)" checked> Комментировать анонимно </label> <div id="anon-fields" style="display:none; margin-top:15px;"> <input type="text" name="author_name" placeholder="Ваше имя" value="<?= e($author_name ?? '') ?>"> <input type="email" name="author_email" placeholder="Email (не публикуется)" value="<?= e($author_email ?? '') ?>"> </div> <textarea name="content" rows="5" placeholder="Текст комментария..."><?= e($content ?? '') ?></textarea> <button type="submit" class="btn">Отправить</button> </form> <script> function toggleAnon(checkbox) { var fields = document.getElementById('anon-fields'); if (checkbox.checked) { fields.style.display = 'none'; } else { fields.style.display = 'block'; } } // Проверяем состояние при загрузке страницы если чекбокс был снят сервером из-за ошибки document.addEventListener('DOMContentLoaded', function() { var cb = document.querySelector('input[name="anonymous"]'); var fields = document.getElementById('anon-fields'); if (!cb.checked) fields.style.display = 'block'; }); </script> </body> </html>