php 實現留言板功能
阿新 • • 發佈:2018-11-16
<?php header('content-type:text/html;charset=utf-8'); /* */ date_default_timezone_set('PRC'); $filename="msg.txt"; $msgs=[]; //檢測檔案是否存在 if(file_exists($filename)){ $string=file_get_contents($filename); if(strlen($string)>0){ $msgs=unserialize($string); } }else { //不存在就建立 #$myfile = fopen($filename, "w"); } //檢測使用者是否點選了提交按鈕 if(isset($_POST['pubMsg'])){ $username=$_POST['username']; $title=strip_tags($_POST['title']); $content=strip_tags($_POST['content']); $time=time(); //將其組成關聯陣列 $data=compact('username','title','content','time'); array_push($msgs,$data); $msgs=serialize($msgs); print_r($msgs); if(file_put_contents($filename,$msgs)){ echo "<script>alert('留言成功!'); location.href='msg.php';</script>"; }else{ echo "<script>alert('留言失敗!'); location.href='msg.php';</script>"; } } ?> <!DOCTYPE html> <html lang="en" dir="ltr"> <head> <meta charset="utf-8"> <title>ootstrap視覺化佈局系統</title> <link rel="stylesheet" href="https://cdn.bootcss.com/bootstrap/3.3.7/css/bootstrap.min.css"> <script src="https://cdn.bootcss.com/jquery/2.1.1/jquery.min.js"></script> <script src="https://cdn.bootcss.com/bootstrap/3.3.7/js/bootstrap.min.js"></script> </head> <body> <div class="container-fluid"> <div class="row-fluid"> <div class="span12"> <div class="page-header"> <h1> 留言板- <small>v1.0</small> </h1> </div> <div class="hero-unit"> <h1> Hello, world! </h1> <p> 這是一個視覺化佈局模板, 你可以點選模板裡的文字進行修改, 也可以通過點選彈出的編輯框進行富文字修改. 拖動區塊能實現排序. </p> <p> <a class="btn btn-primary btn-large" href="#">參看更多 »</a> </p> </div> <?php if(is_array($msgs)&&count($msgs)>0): ?> <table class="table"> <thead> <tr> <th> 編號 </th> <th> 使用者名稱 </th> <th> 標題 </th> <th> 時間 </th> <th> 內容 </th> </tr> </thead> <tbody> <?php $i=1; foreach($msgs as $val): ?> <tr class="success"> <td> <?php echo $i++;?> </td> <td> <?php echo $val['username'];?> </td> <td> <?php echo $val['title'];?> </td> <td> <?php echo date('m/d/Y H:i:s',$val['time']);?> </td> <td> <?php echo $val['content'];?> </td> </tr> <?php endforeach; ?> </tbody> </table> <?php endif; ?> <form action="#" method="post"> <fieldset> <legend>請留言</legend> <label for="">使用者名稱</label> <br/> <input type="text" name="username" value="" required> <br/> <label for="">標題</label> <br/> <input type="text" name="title" value="" required> <br/> <label for="">內容</label> <br/> <textarea name="content" rows="5" cols="30" required></textarea> <hr/> <input type="submit" class="btn btn-primary btn-lg" name="pubMsg" value="釋出留言" > </fieldset> </form> </div> </div> </div> </body> </html>