Okay, we are finally going to involve data storage. Please forgive me for skipping a lot of basic knowledge. I really can’t wait for the actual practice~~Haha!
Simple message board, relying on txt to store data, just an exercise. In the next article, we will have a first experience with the database. This blog post is just a warm-up.
Look at the effect and source code:
##
<?php /** * 简单留言板 */ $filename = "message.txt"; // 写入 // 如果用户提交了,就写入文件,按一定格式写入 if(isset($_POST['dosubmit'])){ $mess = "{$_POST['username']}||".time()."||{$_POST['title']}||{$_POST['content']}[n]"; writeMessage($filename,$mess); } function writeMessage($filename,$mess){ $fp = fopen($filename,"a"); fwrite($fp,$mess); fclose($fp); } // 读取 if (file_exists($filename)){ // 如果文件存在 readMessage($filename); } function readMessage($filename){ $mess = file_get_contents($filename); // file_get_contents() 把整个文件读入一个字符串中 $mess = rtrim($mess,"[n]"); // rtrim() 函数移除字符串右侧的空白字符或其他预定义字符 $arrmess = explode("[n]",$mess); // explode() 函数把字符串打散为数组 foreach ($arrmess as $m){ list($username,$date,$title,$content) = explode("||",$m); // list() 函数用于在一次操作中给一组变量赋值 echo "<b>{$username}</b> ".date("Y-m-d H:i")." {$title},{$content}<br><hr><br>"; } } ?> <!--简单留言板--> <!--textarea 多行文本--> <!--cols="40" 40列--> <!--rows="4" 4行--> <form action="message.php" method="post"> 用户:<input type="text" name="username" value="" /><br> 标题:<input type="text" name="title" value="" /><br> 内容:<textarea cols="40" rows="4" name="content"></textarea><br> <input type="submit" name="dosubmit" value="留言" /><br> </form>