利用fopen,fwrite,fclose,fgetcsv简单的留言本发布和读取功能

index.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>留言本</title>
</head>
<body>
<form action="index.php" method="get">
    <div>标题:<input type="text" name="title"></div>
    <div>内容:<input type="text" name="content"></div>
    <input type="submit" value="提交">
</form>
</body>
</html>

index.php(写入留言本)

$arr=$_GET['title'].','.$_GET['content'];
$fh = fopen('./index.txt', 'a');
fwrite($fh, $arr);
fclose($fh);

fopen如果打开失败,本函数 返回FALSE。打开成功,返回资源类型,例如:resource(3) of type (stream);

readmsg.php(展示全部留言)

//读取指定的第几条
header("content-type:text/html;charset=utf-8");
$i=1;
$fh = fopen('./index.txt', 'r');
while ($re=fgetcsv($fh)){
    echo '<a href="msg.php?tid=',$i,'">',$re[0],'</a>','<br>';
    $i++;
}

效果如下:
实例
msg.php(展示指定留言)

header("content-type:text/html;charset=utf-8");
$tid = $_GET['tid'];
$i = 1;
$fh = fopen('./index.txt', 'r');
while ($re = fgetcsv($fh)) {
    if ($i == $tid) {
        echo '标题:', $re[0], '<br>', '内容:', $re[1], '<br>';
    }
    $i++;
}

效果如下:
实例

fgetcsv与 fgets() 类似,不同的是 fgetcsv() 解析读入的行并找出 CSV 格式的字段,然后返回一个包含这些字段的数组,出错时返回 FALSE,包括碰到文件结束时。fgets返回字符串。
fgetcsv从文件指针中读入一行并解析 CSV 字段

猜你喜欢

转载自blog.csdn.net/coco1118/article/details/82900011