不使用資料庫,直接以檔案系統儲存留言:每筆留言一個文字檔,檔名含時間戳記。包含顯示列表、發表表單、寫入處理三個頁面。
<?php
$path = 'DB/';
$dh = opendir($path);
while (($file = readdir($dh)) !== false) {
if ($file === '.' || $file === '..') continue;
$fp = fopen($path . $file, 'r');
$title = fgets($fp);
$author = fgets($fp);
$content = fread($fp, filesize($path . $file));
fclose($fp);
echo "<b>標題:</b>" . htmlspecialchars($title) . "<br>";
echo "<b>作者:</b>" . htmlspecialchars($author) . "<br>";
echo "<b>內容:</b><pre>" . htmlspecialchars($content) . "</pre>";
echo "<hr>";
}
closedir($dh);
?>
<?php
$path = 'DB/';
$filename = 'S' . date('YmdHis') . '.dat';
$fp = fopen($path . $filename, 'w');
fwrite($fp, $_POST['title'] . "\n");
fwrite($fp, $_POST['author'] . "\n");
fwrite($fp, $_POST['content'] . "\n");
fclose($fp);
echo '留言發表成功! <a href="Index.php">返回首頁</a>';
?>
<!DOCTYPE html> <html><head><meta charset="utf-8"><title>發表留言</title></head><body> <h1 style="text-align:center">發表新的留言</h1> <form method="post" action="Post.php"> <table align="center"> <tr><td>標題</td><td><input name="title" type="text" size="50"></td></tr> <tr><td>作者</td><td><input name="author" type="text" size="20"></td></tr> <tr><td>內容</td><td><textarea name="content" cols="50" rows="10"></textarea></td></tr> </table> <p align="center"><input type="submit" value="送出"> <input type="reset" value="重填"></p> </form> </body></html>
htmlspecialchars(),範例已加入。S{YmdHis}{rand(1000,9999)}.dat)。DB/ 需可寫入,建議設為 0755,擁有者為 PHP 執行身分。flock() 或改用 SQLite/資料庫。