<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
<link rel="stylesheet" href="./global.css" />
</head>
<body>
<div id="one">
<a id="messages"></a>
<?php
// 1.读取留言内容 mysql.txt
$filename = 'mysql.txt';
if (file_exists($filename) && is_readable($filename)) {
// 读取文件内容
$mysql = file_get_contents($filename);
if (!empty($mysql)) {
// 2.将留言内容分割成数组(每条留言以"------------------------"分隔)
$mysqlArray = explode("------------------------", $mysql);
echo '<table>';
echo '<tr><th width="15%">用户名</th><th width="60%">留言内容</th><th width="25%">留言时间</th></tr>';
// 遍历并显示每条留言
foreach ($mysqlArray as $mysql) {
$mysql = trim($mysql);
if (!empty($mysql)) {
// 解析每条留言的各个部分
$lines = explode("\n", $mysql);
$user = str_replace('用户名: ', '', trim($lines[0]));
$content = str_replace('留言内容: ', '', trim($lines[1]));
$time = str_replace('留言时间: ', '', trim($lines[2]));
echo '<tr>';
echo '<td>' . htmlspecialchars($user) . '</td>';
echo '<td>' . nl2br(htmlspecialchars($content)) . '</td>';
echo '<td>' . htmlspecialchars($time) . '</td>';
echo '</tr>';
}
}
echo '</table>';
} else {
echo '<p style="text-align:center;">暂无留言</p>';
}
} else {
echo '<p style="text-align:center;">留言文件不存在或无法读取</p>';
}
?>
</div>
</body>
</html>
<?php
// 1.接收用户输入的内容
$username = isset($_POST['username']) ? trim($_POST['username']) : '';
$content = isset($_POST['content']) ? trim($_POST['content']) : '';
// 验证输入是否为空
if (empty($username) || empty($content)) {
echo '<script>alert("用户名和留言内容不能为空");location="./index.html"</script>';
exit;
}
// 2.将用户输入的内容进行拼接组装
$message = "用户名: " . $username . "\n";
$message .= "留言内容: " . $content . "\n";
$message .= "留言时间: " . date('Y-m-d H:i:s') . "\n";
$message .= "------------------------\n";
// 3.写入到文件中保存
$filename = 'mysql.txt';
// 3.1打开文件(追加模式)
$file = fopen($filename, 'a');
if ($file === false) {
echo '<script>alert("无法打开留言文件");location="./index.html"</script>';
exit;
}
// 3.2写入文件
$result_int = fwrite($file, $message);
// 3.3关闭文件
fclose($file);
// 4.处理结果跳转
if ($result_int) {
echo '<script>alert("留言成功");location="./show.php"</script>';
} else {
echo '<script>alert("留言失败");location="./index.html"</script>';
}
?>
第一段代码写出留言后第二段代码无法实现显示第一段代码留言结果