无需数据库,创建自动更新最新页面链接的index.php及页面生成器
无数据库实现页面生成与索引自动更新
核心思路是用JSON文件存储页面链接信息,代替直接修改index.php的方式——这种方式更安全,不会破坏页面结构,也更容易维护。以下是具体实现步骤:
1. 重构索引页面(index.php 及主内容文件)
include/index_main.php(主内容文件)
修改为动态读取链接列表的形式,自动渲染所有新增页面的链接:
<!DOCTYPE HTML> <html> <body> ... <section> <?php // 读取链接存储文件 $linksFile = __DIR__ . '/../links.json'; $links = []; if (file_exists($linksFile)) { $linksJson = file_get_contents($linksFile); $links = json_decode($linksJson, true) ?: []; // 按创建时间倒序排列,优先显示最新页面 usort($links, function($a, $b) { return strtotime($b['created_at']) - strtotime($a['created_at']); }); } // 遍历生成链接 foreach ($links as $link) { echo "<a href=\"{$link['path']}\">{$link['title']}</a><br>"; } ?> </section> </body> </html>
index.php
保持简洁的include结构即可:
<?php include("include/index_main.php"); ?>
2. 改进页面生成器(pagebuilder.php)
修正原有代码的语法错误,添加生成页面+更新链接存储的逻辑:
<?php // 处理POST提交的页面数据(假设提交了title和content) if ($_SERVER['REQUEST_METHOD'] === 'POST') { $pageTitle = $_POST['title'] ?? '未命名页面'; $pageContent = $_POST['content'] ?? ''; // 生成唯一的页面路径(用时间戳命名,避免重复) $pagePath = 'pages/' . time() . '.html'; // 1. 创建新页面文件 $newPage = fopen($pagePath, 'w'); if ($newPage) { // 写入页面内容(可自定义模板) $fullContent = "<!DOCTYPE HTML><html><head><title>{$pageTitle}</title></head><body>{$pageContent}</body></html>"; fwrite($newPage, $fullContent); fclose($newPage); // 2. 更新链接存储文件 $linksFile = 'links.json'; $existingLinks = []; if (file_exists($linksFile)) { $existingLinksJson = file_get_contents($linksFile); $existingLinks = json_decode($existingLinksJson, true) ?: []; } // 添加新页面信息 $existingLinks[] = [ 'title' => $pageTitle, 'path' => $pagePath, 'created_at' => date('Y-m-d H:i:s') ]; // 写回JSON文件 file_put_contents($linksFile, json_encode($existingLinks, JSON_PRETTY_PRINT)); echo "页面创建成功!<a href='index.php'>返回首页</a>"; } else { echo "无法创建页面,请检查目录权限!"; } } else { // 显示页面创建表单 ?> <form method="POST"> 页面标题:<input type="text" name="title" required><br> 页面内容:<textarea name="content" required></textarea><br> <button type="submit">创建页面</button> </form> <?php } ?>
注意事项
- 确保
pages/目录存在,且PHP有读写权限(可通过chmod 755 pages/设置) links.json文件首次运行会自动创建,需确保PHP有写入权限- 若不需要页面标题,可简化存储结构,只保存路径即可
- 若要避免重复页面名称,可在生成
$pagePath时做重复检查
内容的提问来源于stack exchange,提问作者C9_HP
相关产品推荐
相关产品推荐

