本範例示範使用文字檔(liuyan.txt)作為儲存媒介,實作簡易留言板,包含 新增留言、顯示列表、刪除留言 三大功能,並採用共用 menu.php 做導覽列。
index.php:留言輸入表單doAdd.php:處理新增留言show.php:顯示所有留言del.php:刪除指定留言menu.php:共用導覽列liuyan.txt:資料儲存檔<h2 style="color:blue">我的留言板</h2> <a href="index.php">新增留言</a> <a href="show.php">查看留言</a> <hr width="90%"/>
<form action="doAdd.php" method="post">
<table>
<tr><td align="right">標題:</td><td><input type="text" name="title"/></td></tr>
<tr><td align="right">留言者:</td><td><input type="text" name="author"/></td></tr>
<tr><td align="right" valign="top">內容:</td><td><textarea name="content" rows="5" cols="30"></textarea></td></tr>
<tr><td colspan="2" align="center"><input type="submit" value="送出"> <input type="reset" value="重置"></td></tr>
</table>
</form>
$title = $_POST["title"];
$author = $_POST["author"];
$content = $_POST["content"];
$time = time();
$ip = $_SERVER["REMOTE_ADDR"];
$ly = "{$title}##{$author}##{$content}##{$time}##{$ip}@@@";
$ly .= file_get_contents("liuyan.txt");
file_put_contents("liuyan.txt", $ly);
$info = file_get_contents("liuyan.txt");
if ($info) {
$info = rtrim($info, "@");
$lylist = explode("@@@", $info);
foreach ($lylist as $key => $v) {
$ly = explode("##", $v);
echo "<tr>";
echo "<td align='center'>{$ly[0]}</td>";
echo "<td align='center'>{$ly[1]}</td>";
echo "<td align='center'>{$ly[2]}</td>";
echo "<td>".date("Y-m-d H:i:s", $ly[3]+8*3600)."</td>";
echo "<td>{$ly[4]}</td>";
echo "<td><a href='del.php?id={$key}'>刪除</a></td>";
echo "</tr>";
}
}
$id = $_GET["id"];
$info = file_get_contents("liuyan.txt");
$lylist = explode("@@@", $info);
unset($lylist[$id]);
$ninfo = implode("@@@", $lylist);
file_put_contents("liuyan.txt", $ninfo);
每筆留言以 @@@ 分隔,欄位間以 ## 分隔:
標題##作者##內容##時間戳##IP@@@
htmlspecialchars() 防 XSS此範例適合入門理解 PHP 檔案讀寫與基本 CRUD 邏輯。