php demo之基于文件的留言本

本文介绍了一个简单的基于文件的留言本实现方案,通过PHP语言完成用户留言的提交与显示功能,无需数据库支持,适用于轻量级应用或学习场景。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

该demo一共有3个文件
index.php write.php message.text

index.php

<div class="textBox" style="width: 400px;height: 360px;padding-left: 20px;padding-right: 30px;padding-top: 10px;background: pink;margin:40px auto;">
    <h2 style="text-align:center;margin-bottom: 30px;color: #333;">基于文件的留言本</h2>
    <form action="write.php" method="post">
        <label style="display: inline-block;width: 80px;">用户名:</label><input type="text" name="username" style="border: none;outline: none;width:200px;height: 30px;"/><br/><br/>
        <label style="display: inline-block;width: 80px;vertical-align: top">留言内容:</label><textarea  name="content" rows="10" cols="40" style="border: none;outline: none"></textarea><br/>
        <input type="submit" value="提交" style="margin-top: 20px;margin-bottom: 20px;width: 60px;height: 30px;border: none;background: #000;color: #fff;margin-left:190px;border-radius:5px;outline: none;"/>
    </form>
</div>
<?php
    //设置时区
    date_default_timezone_set('Asia/Shanghai');
    //读了内容
//    变量前面加上@目的防止报错信息输出:在打开文件出错时并不会将报错信息输出给客户端,防止泄露信息.
    @$string = file_get_contents('message.txt');
    //如果$string 不为空的时候执行,也就是message.txt中有留言数据
    if (!empty($string)) {
        //每一段留言有一个分格符,但是最后多出了一个&^。因此,我们要将&^删掉   rtime:从字符串右侧移除字符
        $string = rtrim($string, '&^');
        //以&^切成数组   explode:把字符串打散为数组:
        $arr = explode('&^', $string);
        //将留言内容读取
        foreach ($arr as $value) {
            //将用户名和内容分开
            list($username, $content, $time) = explode('$#', $value);
            echo '<span style="color:pink;margin-right: 17px;">用户名:</span>' . $username . '<br/><span style="color:pink;">留言内容:</span>' . $content . '<br/><span style="color: pink;">留言时间:</span>' . date('Y-m-d H:i:s', $time);
            echo '<hr />';
        }
    }

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');

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值