Example file guestbook
Next let’s take a look at the demonstration effect:
The form interface for writing message content in the following interface:
? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ?
The display interface after leaving a message :
Let’s take a look at the file structure:
index.php --- Display input box and message content
write.php ---Write data to message.txt
message.txt ---Save chat content
<?Php //設置時區(qū) date_default_timezone_set('PRC'); //讀了內(nèi)容 @$string = file_get_contents('message.txt'); //如果$string 不為空的時候執(zhí)行,也就是message.txt中有留言數(shù)據(jù) if (!empty($string)) { //每一段留言有一個分格符,但是最后多出了一個&^。因此,我們要將&^刪掉 $string = rtrim($string, '&^'); //以&^切成數(shù)組 $arr = explode('&^', $string); //將留言內(nèi)容讀取 foreach ($arr as $value) { //將用戶名和內(nèi)容分開 list($username, $content, $time) = explode('$#', $value); echo '用戶名為<font color="gree">' . $username . '</font>內(nèi)容為<font color="red">' . $content . '</font>時間為' . date('Y-m-d H:i:s', $time); echo '<hr />'; } } ?> <h1>基于文件的留言本演示</h1> <form action="write.php" method="post"> 用戶名:<input type="text" name="username" /><br /> 留言內(nèi)容:<textarea name="content"></textarea><br /> <input type="submit" value="提交" /> </form>See Based on the content just shown, we know that when the file is stored: 1. The segments are divided into segments2. The content and the user are separated using a special symbol Let’s write write.php code to write messages to files:
<?php //追加方式打開文件 $fp=fopen('message.txt','a'); //設置時間 $time=time(); //得到用戶名 $username=trim($_POST['username']); //得到內(nèi)容 $content=trim($_POST['content']); //組合寫入的字符串:內(nèi)容和用戶之間分開,使用$# //行與行之間分開,使用&^ $string=$username.'$#'.$content.'$#'.$time.'&^'; //寫入文件 fwrite($fp,$string); //關閉文件 fclose($fp); header('location:index.php'); ?>Create a new text file message.txt