Home  >  Article  >  Backend Development  >  Detailed introduction to the example code for implementing the message board function in PHP

Detailed introduction to the example code for implementing the message board function in PHP

黄舟
黄舟Original
2017-03-27 09:12:191809browse

This article mainly introduces the relevant information of PHP to implement the message board function in detail. It has certain reference value. Interested friends can refer to the examples of

I have shared with you the implementation ideas of php message board for your reference. The specific content is as follows

1. Create a file name to store message information

2. Get the data in the form and give it to a variable

3. It exists when judging the file

4. Perform the write operation on the file. Before doing this, pay attention to selecting the access method to the file when opening the file, and finally remember to close the file

5. Perform a read operation on the file, and remember to close the file at the end

<?php

//留言板的思路:1.先创建一个文件名,方便于存放写入的内容
//  2.将表单中的内容赋值给一个变量
  //3.判断文件是否存在,将用户输入的值写进变量,打开文件的是时候注意选择对文件访问的操作
  //4.读取文件的内容,关闭文件


 header("Content-Type:text/html;charset=utf8");
 $filename = "message.txt";//创建一个文件的名字

 //如果用户提交了, 就写入文件, 按一定格式写入
 if(isset($_POST[&#39;dosubmit&#39;])) {
 //字段的分隔使用||, 行的分隔使用[n]
 $mess = "{$_POST[&#39;username&#39;]}||".time()."||{$_POST[&#39;title&#39;]}||{$_POST[&#39;content&#39;]}[n]";


 writemessage($filename, $mess);//向文件写进内容

 }

 if(file_exists($filename)) {//判断文件 是否存在
 readmessage($filename);//读取文件的函数
 }


 function writemessage($filename, $mess) {
 $fp = fopen($filename, "a");//在尾部执行写的操作,且不删除原来的文件内容
 
 fwrite($fp, $mess);//写入文件

 fclose($fp);//关闭文件
 }

 function readmessage($filename) {
 $mess = file_get_contents($filename);
 
 $mess = rtrim($mess, "[n]");

 $arrmess = explode("[n]", $mess);

 foreach($arrmess as $m) {
  list($username, $dt ,$title, $content) = explode("||", $m);

  echo "<b>{$username}</b>, ".date("Y-m-d H:i").": <i>{$title}</i>, <u>{$content}</u><br><hr><br>";
 }

 }

?>

<form action="message.php" method="post">
 用户: <input type="text" name="username" value="" /><br>
 标题:<input type="text" name="title" value="" /><br>
 内容:<textarea name="content" cols="40" rows="4"></textarea><br>
 <input type="submit" name="dosubmit" value="留言" /><br>
</form>

The above is the detailed content of Detailed introduction to the example code for implementing the message board function in PHP. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn