PHP implements ...LOGIN

PHP implements file guestbook

We have talked so much about file processing systems, but we can't even write the most basic thing.

Starting from this section, you will find that you can write more and more things.

Next let’s take a look at the demonstration effect:

The form interface for writing message content in the following interface:

444.png

The display interface after leaving a message:

document_2015-09-09_55efe0764ff3c.png


Let’s take a look at the file structure:

index.php ---Display input box and message content
write.php ---Write data to message.txt
message.txt ---Save chat content

index.php File

<?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 $value) {
        //将用户名和内容分开
        list($username, $content, $time) = explode('$#', $value);
        echo '用户名为<font color="gree">' . $username . '</font>内容为<font color="red">' . $content . '</font>时间为' . date('Y-m-d H:i:s', $time);
        echo '<hr />';
    }
}
?>
<h1>基于文件的留言本演示</h1>
<form action="write.php" method="post">
    用户名:<input type="text" name="username" /><br />
    留言内容:<textarea  name="content"></textarea><br />
    <input type="submit" value="提交" />
</form>

After looking at the display content just now, we know that when the file is stored:

1. The segments are divided into segments

2. The content is the same as what the user has previously used A special symbol is used to separate it.

Let’s write write.php code to write messages to the file:

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

?>


Next Section
<?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'); ?>
submitReset Code
ChapterCourseware