该demo一共有3个文件
index.php write.php message.text
index.php
<div class="textBox" style="width: 400px;height: 360px;padding-left: 20px;padding-right: 30px;padding-top: 10px;background: pink;margin:40px auto;">
<h2 style="text-align:center;margin-bottom: 30px;color: #333;">基于文件的留言本</h2>
<form action="write.php" method="post">
<label style="display: inline-block;width: 80px;">用户名:</label><input type="text" name="username" style="border: none;outline: none;width:200px;height: 30px;"/><br/><br/>
<label style="display: inline-block;width: 80px;vertical-align: top">留言内容:</label><textarea name="content" rows="10" cols="40" style="border: none;outline: none"></textarea><br/>
<input type="submit" value="提交" style="margin-top: 20px;margin-bottom: 20px;width: 60px;height: 30px;border: none;background: #000;color: #fff;margin-left:190px;border-radius:5px;outline: none;"/>
</form>
</div>
<?php
//设置时区
date_default_timezone_set('Asia/Shanghai');
//读了内容
// 变量前面加上@目的防止报错信息输出:在打开文件出错时并不会将报错信息输出给客户端,防止泄露信息.
@$string = file_get_contents('message.txt');
//如果$string 不为空的时候执行,也就是message.txt中有留言数据
if (!empty($string)) {
//每一段留言有一个分格符,但是最后多出了一个&^。因此,我们要将&^删掉 rtime:从字符串右侧移除字符
$string = rtrim($string, '&^');
//以&^切成数组 explode:把字符串打散为数组:
$arr = explode('&^', $string);
//将留言内容读取
foreach ($arr as $value) {
//将用户名和内容分开
list($username, $content, $time) = explode('$#', $value);
echo '<span style="color:pink;margin-right: 17px;">用户名:</span>' . $username . '<br/><span style="color:pink;">留言内容:</span>' . $content . '<br/><span style="color: pink;">留言时间:</span>' . date('Y-m-d H:i:s', $time);
echo '<hr />';
}
}
write.php
<?php
//追加方式打开文件
$fp=fopen('message.txt','a');
//设置时间
$time=time();
//得到用户名
$username=trim($_POST['username']);
//得到内容
$content=trim($_POST['content']);
//组合写入的字符串:内容和用户之间分开,使用$#
//行与行之间分开,使用&^
$string=$username.'$#'.$content.'$#'.$time.'&^';
//写入文件
fwrite($fp,$string);
//关闭文件
fclose($fp);
header('location:index.php');