Вывод статей в блоге. PHP
Делаю не большой блог. Статьи у меня хранятся в текстовых файлах (01.txt, 02.txt ...), так как до изучения БД я еще не дошел. Статья может добавляться, либо из файла admin.php либо вручную создать файл. При первом заходе производится обход всех файлов, они добавляются в массив $articles и ставиться сессия, ну чтобы каждый раз не делать цикл по всем файлам. Проблема в том, что когда сессия установлена - новая статья не отображается.
<?php require_once 'search.php'; error_reporting(E_ALL); session_start(); define('USER_NAME', 'admin'); define('PASSWORD', '123'); if (isset($_GET['do']) && $_GET['do'] == 'logout') { unset($_SESSION['auth']); header("Location: /index.php"); die(); } if (isset($_POST['auth'])) { if ($_POST['login'] == USER_NAME && $_POST['password'] == PASSWORD) { $_SESSION['auth'] = true; header("Location: /admin.php"); } else { header("Location: /index.php"); } exit(); } $articles = []; if (!isset($_SESSION['articles'])) { $dir = opendir('articles'); if ($dir) { while (($file = readdir($dir)) !== false) { if ($file != "." && $file != ".." && is_file('articles/' . $file)) { $content = file_get_contents('articles/' . $file); if ($content !== false) { $article = explode("[separator]", $content); $articles[$article[0]] = $article[1]; } else { echo "Не удалось прочитать содержимое файла: $file <br>"; } } } closedir($dir); } else { echo "Не удалось открыть директорию 'articles'"; } $_SESSION['articles'] = $articles; } else { $articles = $_SESSION['articles']; } $items_per_page = 3; $current_page = isset($_GET['page']) ? $_GET['page'] : 1; $total_items = count($articles); $total_pages = ceil($total_items / $items_per_page); $start_index = ($current_page - 1) * $items_per_page; $end_index = $start_index + $items_per_page - 1; $display_data = array_slice($articles, $start_index, $items_per_page); ?> <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>My blog</title> <link rel="stylesheet" href="/style.css"> </head> <body> <header> <h1><a href="index.php">My Blog</a></h1> <?php if (isset($_SESSION['auth'])) { ?> <p style="color: green"> Вы авторизовались как Admin! <a href="?do=logout">Выход</a> </p> <?php } else { ?> <form action="" method="POST"> <fieldset> <legend>Вход</legend> <input type="text" name="login"> <input type="password" name="password"> <input type="submit" name="auth" value="Авторизоваться"> </fieldset> </form> <?php } ?> <form action="search.php" method="GET"> <fieldset> <legend>Поиск</legend> <input type="text" name="search"> <input type="submit" value="Искать"> </fieldset> </form> </header> <main> <?php foreach ($display_data as $key => $value) { ?> <article> <h2><?= $key ?></h2> <?= $value ?> </article> <?php } ?> </main> <footer> <div> <?php if ($current_page > 1) { echo "<a href='?page=" . ($current_page - 1) . "'>Previous</a> "; } for ($i = 1; $i <= $total_pages; $i++) { echo "<a href='?page=$i'>$i</a> "; } if ($current_page < $total_pages) { echo "<a href='?page=" . ($current_page + 1) . "'>Next</a>"; } ?> </div> </footer> </body> </html> Как правильно это сделать? Не хочется при каждом запросе делать цикл. Это как-то не правильно, кмк. |
Попробуйте кешировать не в сессию, а в какой-нибудь отдельный файл. После добавления новой "статьи" просто удаляйте этот файл.
Для кеша файл сессии не лучшее место. |
Nexus,
спасибо. Хорошая идея. |
Часовой пояс GMT +3, время: 17:52. |