PHP语言基础知识10 PHP实现文件留言本

文件结构:

index.php  展示输入框和留言内容

write.php   向message.txt写入数据

message.txt  存入聊天内容

 

编写index.php文件信息:

<?php

//设置时区

date_default_timezone_set('PRC');

//读了内容

@$string=file_get_contents('message.txt');

//如果string不为空的时候执行,也就是message.txt中有留言数据

    if(!empty($string)){

     //每一段留言有一个分隔符,但是最后多出一个&^,因此我们要将&^删除掉
   
     $string=rtrim($string,'&^');
    
     //以&^切成数组
     
     $arr=explode('&^',$string);
   
      //将留言内容读取
    
    foreach($arr as $vaule){
    
     //将用户名和内容分开
    
    list($username,$content,$time)=explode('$#',$value);
 
     echo '用户名为<font color="green">'.$username.'</font>内容为<font color="red">'.$conten.'</font>时间为'.date('Y-m-d H:i:s',$time);
    
       echo'<hr />';
       }
}
?>

<h1>基于文件的留言本演示</h1>

<rorm action="write.php" method="post">
        用户名: <input type="text" name="username"/><br />
        留言内容: <textarea name="conten"></textarea><br />
        <input type="submit" value="提交" />
</form>

看了刚刚的展示内容,我们知道文件存储时:

  • 段与段之间进行了分隔
  • 内容与用户之前用一个特殊的符号进行了分隔

下面我们来写write.php写入留言至文件的代码:

<?php

//追加方式打开文件

$fp=fopen('message.txt'','a');

//设置时间

$time=time();

//得到用户名

$username=trim($_POST['username']);

//得到内容

$content=trim($_POST['content']);

//组合写入的字符串: 内容和用户名之间分开,使用$#
//航宇航之间分开使用&^

$string=$username.'$#'.$content.'$#'.$time.'&^';

//写入文件

fwrite($fp,$string);

//关闭文件

fclose($fp);

header('location:index.php');
?>

 

posted @ 2020-09-27 14:51  阿澈  阅读(243)  评论(0)    收藏  举报