萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 網頁製作 >> HTML 腳本教學

PHP 靜態文章發布系統:從表單輸入到 HTML 生成的極簡實作

輕量級 PHP 靜態站點生成器:管理員登入 → 文章編輯(FCKeditor) → 靜態 HTML 生成 → 索引頁自動更新。核心邏輯僅需 4 個檔案與目錄寫入權限。

系統架構

  1. session.php:管理員身份驗證
  2. getip.php:客戶端 IP 取得(輔助驗證)
  3. html.php:統一入口(登入/發文/生成)
  4. templates/article.tpl:文章頁面模板
  5. data/index.txt:文章索引(檔名|標題|時間)

核心生成流程

// 1. 組裝完整 HTML 字串
$html = file_get_contents('templates/article.tpl');
$html = str_replace('{TITLE}', $_POST['title'], $html);
$html = str_replace('{CONTENT}', $_POST['content'], $html);

// 2. 檔名採時間戳確保唯一
$filename = date('YmdHis') . '.html';
file_put_contents("articles/$filename", $html);

// 3. 更新索引檔(預置新行)
$indexLine = "$filename|{$_POST['title']}|" . date('Y-m-d H:i:s') . "\n";
file_put_contents('data/index.txt', $indexLine . file_get_contents('data/index.txt'));

索引頁生成邏輯

$lines = file('data/index.txt', FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
$listHtml = '';
foreach ($lines as $line) {
  [$file, $title, $time] = explode('|', $line);
  $listHtml .= "<li><a href='articles/$file'>$title</a> <span>$time</span></li>";
}
$indexTpl = file_get_contents('templates/index.tpl');
$indexTpl = str_replace('{LIST}', $listHtml, $indexTpl);
file_put_contents('index.html', $indexTpl);

擴充建議

  • 分頁:索引陣列 array_chunk 分組生成 index-1.html、index-2.html
  • 分類:索引增加分類欄位,生成 category-xxx.html
  • RSS/Atom:遍歷索引輸出 XML Feed
  • 安全:CSRF Token、輸入過濾(HTMLPurifier)、目錄執行權限移除
copyright © 萬盛學電腦網 all rights reserved