PHP实现留言板功能的详细代码
博主:紫藤心-迷途
浏览次数:1234次
本文实例为大家分享了php留言板的实现思路,供大家参考(这是最初级的,大佬勿喷!),具体内容如下
1.创建一个存放留言信息的文件名
2.获取表单中的数据给一个变量
3.判断文件的时候存在
4.对文件执行写的操作,在这之前,注意打开文件的时候,选择对文件的访问方式,最后记得关闭文件
5.对文件执行读的操作,同样最后要记得关闭文件
首先创建一个index.php页面,用于提交内容信息,完整代码如下:
<html> <head> <title>留言板</title> <style> .mian{width:100%;margin:0 auto;} table tr th,table tr td{padding:5px;} </style> </head> <body> <div class="mian"> <div class="add"> <h2>个人留言版系统</h2> <form action="message.php" method="post"> <p>留言姓名:<input type="text" value="" name="username"></p> <p>留言内容:<textarea cols="30" rows="4" name="comment"></textarea></p> <p>联系方式:<input type="text" value="" name="iphone"></p> <p><input type="submit" value="提交" name="submit"> <input type="reset" name="reset" value="重置"></p> </form> </div> <div class="message"> <h2>留言信息展示</h2> <?php $filename = "message.txt"; $mess = file_get_contents($filename); $mess = rtrim($mess,"[n]"); $arrmess = explode("[n]", $mess); echo '<table cellspacing="0" cellpadding="0" border="1">'; echo '<thead><tr>'; echo '<th>姓名</th>'; echo '<th>留言内容</th>'; echo '<th>联系方式</th>'; echo '<th>留言时间</th>'; echo '</tr></thead>'; foreach($arrmess as $m) { list($username, $comment ,$iphone) = explode("||", $m); echo '<tr>'; echo '<td>' .$username.'</td>'; echo '<td>' .$comment.'</td>'; echo '<td>' .$iphone.'</td>'; echo '<td>' .date("Y-m-d").'</td>'; echo '</tr>'; } echo '</table>'; ?> </div> </div> </body> </html>
最后创建message.php处理文件,详细代码如下:
<?php if($_POST['username'] !='' && $_POST['comment'] !='' && $_POST['iphone'] !=''){ $username = $_POST['username']; $comment = $_POST['comment']; $iphone = $_POST['iphone']; }else{ echo "<script>alert('请填写正确,内容不能为空!'); window.location.href='/index.php';</script>"; die(); } $file = fopen('message.txt','a') or die("文件不存在!"); $text ="$username||$comment||$iphone||".time()."[n]"; fwrite($file,$text); fclose($file); echo"<script>alert('留言提交成功!'); window.location.href='/index.php';</script>"; ?>
哈哈,这就完成了,希望对刚开始接触编程的你有所帮助!