以下是一个简单的论坛程序的PHP代码示例:
index.php:
<?php
session_start();
// 检查用户是否已登录
if (!isset($_SESSION['username'])) {
header('Location: login.php');
exit;
}
// 获取当前用户
$username = $_SESSION['username'];
// 处理用户提交的帖子
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
$title = $_POST['title'];
$content = $_POST['content'];
// 保存帖子到数据库
savePost($username, $title, $content);
}
// 获取所有帖子
$posts = getPosts();
// 显示论坛页面
include 'forum.php';
login.php:
<?php
session_start();
// 处理用户提交的登录表单
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
$username = $_POST['username'];
$password = $_POST['password'];
// 检查用户名和密码是否正确
if (checkCredentials($username, $password)) {
// 登录成功,将用户名保存到session中
$_SESSION['username'] = $username;
header('Location: index.php');
exit;
} else {
$error = '用户名或密码错误';
}
}
// 显示登录页面
include 'login_form.php';
forum.php:
<!DOCTYPE html>
<html>
<head>
<title>论坛</title>
</head>
<body>
<h1>欢迎来到论坛</h1>
<h2>当前用户:<?php echo $username; ?></h2>
<h3>发表新帖子</h3>
<form method="POST" action="index.php">
<label for="title">标题:</label>
<input type="text" name="title" id="title" required><br>
<label for="content">内容:</label>
<textarea name="content" id="content" required></textarea><br>
<input type="submit" value="发表">
</form>
<h3>帖子列表</h3>
<?php foreach ($posts as $post): ?>
<h4><?php echo $post['title']; ?></h4>
<p><?php echo $post['content']; ?></p>
<hr>
<?php endforeach; ?>
</body>
</html>
login_form.php:
<!DOCTYPE html>
<html>
<head>
<title>登录</title>
</head>
<body>
<h1>登录</h1>
<?php if (isset($error)): ?>
<p><?php echo $error; ?></p>
<?php endif; ?>
<form method="POST" action="login.php">
<label for="username">用户名:</label>
<input type="text" name="username" id="username" required><br>
<label for="password">密码:</label>
<input type="password" name="password" id="password" required><br>
<input type="submit" value="登录">
</form>
</body>
</html>
请注意,这只是一个简单的示例,实际的论坛程序需要更多的功能和安全性措施。
Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3
Laravel 中文站