靜態化優勢
- SEO 友好:搜索引擎更易抓取靜態頁
- 性能提升:減輕 Apache/PHP 解析壓力
- 安全性:隱藏後端邏輯與數據庫結構
三文件協作架構
1. addform.html - 前端提交表單
<form action="add.php" method="post">
新聞標題:<br>
<input type="text" name="title" /><br>
新聞內容:<br>
<textarea name="content" rows="10" cols="50"></textarea><br>
<input type="submit" name="submit" value="提交"/>
</form>
2. add.php - 核心處理邏輯
<?php
require_once("mysql_inc.php"); // 數據庫連接
$title = $_POST['title'];
$content = $_POST['content'];
// 文件計數器:生成遞增文件名 1.html, 2.html...
$countfile = "count.txt";
if (!file_exists($countfile)) fopen($countfile, "w");
$fp = fopen($countfile, "r");
$num = (int)fgets($fp, 20) + 1;
fclose($fp);
$fp = fopen($countfile, "w");
fwrite($fp, $num);
fclose($fp);
$path = $num . ".html"; // 如 1.html
// 寫入數據庫
$sql = "INSERT INTO news (id, title, content, path) VALUES (NULL, '$title', '$content', '$path')";
mysql_query($sql);
// 模板替換生成靜態頁
$fp = fopen("mode.html", "r");
$str = fread($fp, filesize("mode.html"));
fclose($fp);
$str = str_replace("{title}", $title, $str);
$str = str_replace("{content}", $content, $str);
$handle = fopen($path, "w");
fwrite($handle, $str);
fclose($handle);
echo "<a href='$path' target='_blank'>查看剛才生成的新聞</a>";
?>
3. mode.html - 模板文件
<html>
<head><title>{title}</title></head>
<body>
<h1>{title}</h1>
<div>{content}</div>
</body>
</html>
4. mysql_inc.php - 數據庫連接類(簡化版)
<?php
class MySQL {
private $link;
public function __construct($host, $user, $pass, $db, $charset = 'utf8') {
$this->link = mysql_connect($host, $user, $pass) or die(mysql_error());
mysql_select_db($db, $this->link) or die(mysql_error());
mysql_query("SET NAMES '$charset'", $this->link);
}
public function query($sql) {
return mysql_query($sql, $this->link);
}
public function insert_id() {
return mysql_insert_id($this->link);
}
public function close() {
mysql_close($this->link);
}
}
$db = new MySQL("localhost", "root", "", "database", "utf8");
?>
關鍵技術點
| 技術點 | 實現方式 |
| 文件命名 | 計數器文件 count.txt 實現遞增命名 |
| 模板引擎 | str_replace() 替換 {title} {content} 佔位符 |
| 靜態文件寫入 | fopen($path, "w") + fwrite() |
| 數據持久化 | MySQL 存儲元數據(id, title, content, path) |
現代化改進建議
- **模板引擎**:引入 Smarty、Blade 或 Twig,支援邏輯判斷、循環、繼承
- **計數器並發安全**:使用
flock() 或 Redis 原子增長替代文件計數
- **SQL 注入防護**:使用 PDO 預處理語句替代字串拼接
- **靜態文件部署**:生成至 Nginx 直接服務的目錄,配合 CDN 加速
- **緩存失效策略**:內容更新時重新生成或刪除對應靜態文件
- **異步生成**:大流量時將生成任務推入隊列(如 RabbitMQ)由 Worker 處理
完整流程圖解
用戶提交表單
↓
add.php 接收數據
↓
更新計數器 → 生成文件名 (N.html)
↓
寫入數據庫 (元數據)
↓
讀取模板 mode.html
↓
替換佔位符 {title} {content}
↓
寫入靜態文件 N.html
↓
返回預覽鏈接
- 上一篇文章: PHP 專業身份證驗證類:校驗碼算法與 15/18 位轉換實現
- 下一篇文章: 微信公眾平台開發實戰:使用 PHP CURL 模擬登錄與數據採集
Copyright ©
程式碼之家 All Rights Reserved