PHP 简易发布系统怎么做

wen PHP项目 3

本文目录导读:

PHP 简易发布系统怎么做

  1. 系统结构设计
  2. 数据库设计
  3. 核心代码实现
  4. 前台页面
  5. 后台管理
  6. 样式文件 (style.css)
  7. 使用说明

我来帮你设计一个PHP简易发布系统,这是一个适合初学者的完整方案:

系统结构设计

simple-cms/
├── index.php          # 前台首页
├── admin/
│   ├── login.php      # 后台登录
│   ├── dashboard.php  # 后台管理
│   ├── post_edit.php  # 文章编辑
│   └── logout.php     # 退出登录
├── includes/
│   ├── config.php     # 配置文件
│   ├── db.php         # 数据库连接
│   └── functions.php  # 公共函数
└── assets/
    └── css/
        └── style.css  # 样式文件

数据库设计

-- 创建数据库
CREATE DATABASE simple_cms;
-- 用户表
CREATE TABLE users (
    id INT AUTO_INCREMENT PRIMARY KEY,
    username VARCHAR(50) UNIQUE NOT NULL,
    password VARCHAR(255) NOT NULL,
    created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
);
-- 文章表
CREATE TABLE posts (
    id INT AUTO_INCREMENT PRIMARY KEY,VARCHAR(200) NOT NULL,
    content TEXT NOT NULL,
    user_id INT,
    created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
    updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
    status ENUM('published', 'draft') DEFAULT 'published',
    FOREIGN KEY (user_id) REFERENCES users(id)
);

核心代码实现

config.php - 配置文件

<?php
// 数据库配置
define('DB_HOST', 'localhost');
define('DB_USER', 'root');
define('DB_PASS', '');
define('DB_NAME', 'simple_cms');
// 站点配置
define('SITE_NAME', '我的发布系统');
define('SITE_URL', 'http://localhost/simple-cms/');
define('UPLOAD_DIR', __DIR__ . '/../uploads/');
// 会话配置
session_start();
error_reporting(E_ALL);
date_default_timezone_set('Asia/Shanghai');
?>

db.php - 数据库连接

<?php
require_once 'config.php';
function getDB() {
    static $db = null;
    if ($db === null) {
        try {
            $db = new PDO(
                "mysql:host=" . DB_HOST . ";dbname=" . DB_NAME . ";charset=utf8",
                DB_USER,
                DB_PASS,
                [
                    PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
                    PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC
                ]
            );
        } catch (PDOException $e) {
            die("数据库连接失败: " . $e->getMessage());
        }
    }
    return $db;
}
?>

functions.php - 公共函数

<?php
require_once 'db.php';
// 检查登录状态
function isLoggedIn() {
    return isset($_SESSION['user_id']);
}
// 获取当前用户
function currentUser() {
    if (!isLoggedIn()) return null;
    $db = getDB();
    $stmt = $db->prepare("SELECT * FROM users WHERE id = ?");
    $stmt->execute([$_SESSION['user_id']]);
    return $stmt->fetch();
}
// 获取所有文章
function getPosts() {
    $db = getDB();
    $stmt = $db->query("SELECT p.*, u.username FROM posts p 
                        LEFT JOIN users u ON p.user_id = u.id 
                        ORDER BY p.created_at DESC");
    return $stmt->fetchAll();
}
// 获取单篇文章
function getPost($id) {
    $db = getDB();
    $stmt = $db->prepare("SELECT * FROM posts WHERE id = ?");
    $stmt->execute([$id]);
    return $stmt->fetch();
}
// 创建文章
function createPost($title, $content, $userId) {
    $db = getDB();
    $stmt = $db->prepare("INSERT INTO posts (title, content, user_id) VALUES (?, ?, ?)");
    return $stmt->execute([$title, $content, $userId]);
}
// 更新文章
function updatePost($id, $title, $content) {
    $db = getDB();
    $stmt = $db->prepare("UPDATE posts SET title = ?, content = ? WHERE id = ?");
    return $stmt->execute([$title, $content, $id]);
}
// 删除文章
function deletePost($id) {
    $db = getDB();
    $stmt = $db->prepare("DELETE FROM posts WHERE id = ?");
    return $stmt->execute([$id]);
}
// 安全输出
function e($str) {
    return htmlspecialchars($str, ENT_QUOTES, 'UTF-8');
}
function excerpt($content, $length = 200) {
    return mb_substr($content, 0, $length, 'UTF-8') . '...';
}
?>

前台页面

index.php - 首页

<?php
require_once 'includes/functions.php';
$posts = getPosts();
?>
<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8"><?php echo SITE_NAME; ?></title>
    <link rel="stylesheet" href="assets/css/style.css">
</head>
<body>
    <header>
        <h1><?php echo SITE_NAME; ?></h1>
        <nav>
            <a href="index.php">首页</a>
            <a href="admin/login.php">后台管理</a>
        </nav>
    </header>
    <div class="container">
        <?php foreach ($posts as $post): ?>
            <article class="post">
                <h2><?php echo e($post['title']); ?></h2>
                <div class="meta">
                    <span>作者: <?php echo e($post['username']); ?></span>
                    <span>时间: <?php echo date('Y-m-d H:i', strtotime($post['created_at'])); ?></span>
                </div>
                <div class="content">
                    <?php echo nl2br(excerpt($post['content'])); ?>
                </div>
                <a href="post.php?id=<?php echo $post['id']; ?>" class="read-more">阅读全文</a>
            </article>
        <?php endforeach; ?>
        <?php if (empty($posts)): ?>
            <p>暂无文章</p>
        <?php endif; ?>
    </div>
</body>
</html>

后台管理

login.php - 登录页面

<?php
require_once '../includes/functions.php';
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $username = $_POST['username'] ?? '';
    $password = $_POST['password'] ?? '';
    $db = getDB();
    $stmt = $db->prepare("SELECT * FROM users WHERE username = ?");
    $stmt->execute([$username]);
    $user = $stmt->fetch();
    if ($user && password_verify($password, $user['password'])) {
        $_SESSION['user_id'] = $user['id'];
        header('Location: dashboard.php');
        exit;
    } else {
        $error = "用户名或密码错误";
    }
}
?>
<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">登录 - <?php echo SITE_NAME; ?></title>
    <link rel="stylesheet" href="../assets/css/style.css">
</head>
<body>
    <div class="login-form">
        <h2>后台登录</h2>
        <?php if (isset($error)): ?>
            <p class="error"><?php echo $error; ?></p>
        <?php endif; ?>
        <form method="POST" action="">
            <div>
                <label>用户名:</label>
                <input type="text" name="username" required>
            </div>
            <div>
                <label>密码:</label>
                <input type="password" name="password" required>
            </div>
            <button type="submit">登录</button>
        </form>
    </div>
</body>
</html>

dashboard.php - 后台管理首页

<?php
require_once '../includes/functions.php';
// 检查登录状态
if (!isLoggedIn()) {
    header('Location: login.php');
    exit;
}
$user = currentUser();
$posts = getPosts();
// 处理删除操作
if (isset($_GET['action']) && $_GET['action'] === 'delete' && isset($_GET['id'])) {
    deletePost($_GET['id']);
    header('Location: dashboard.php');
    exit;
}
?>
<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">后台管理 - <?php echo SITE_NAME; ?></title>
    <link rel="stylesheet" href="../assets/css/style.css">
</head>
<body>
    <header>
        <h1>后台管理</h1>
        <nav>
            <span>欢迎, <?php echo e($user['username']); ?></span>
            <a href="post_edit.php">发布新文章</a>
            <a href="logout.php">退出登录</a>
        </nav>
    </header>
    <div class="container">
        <h2>文章列表</h2>
        <?php if (empty($posts)): ?>
            <p>暂无文章</p>
        <?php else: ?>
            <table>
                <tr>
                    <th>标题</th>
                    <th>作者</th>
                    <th>发布时间</th>
                    <th>操作</th>
                </tr>
                <?php foreach ($posts as $post): ?>
                <tr>
                    <td><?php echo e($post['title']); ?></td>
                    <td><?php echo e($post['username']); ?></td>
                    <td><?php echo date('Y-m-d H:i', strtotime($post['created_at'])); ?></td>
                    <td>
                        <a href="post_edit.php?id=<?php echo $post['id']; ?>">编辑</a>
                        <a href="?action=delete&id=<?php echo $post['id']; ?>" 
                           onclick="return confirm('确定要删除吗?')">删除</a>
                    </td>
                </tr>
                <?php endforeach; ?>
            </table>
        <?php endif; ?>
    </div>
</body>
</html>

post_edit.php - 文章编辑

<?php
require_once '../includes/functions.php';
// 检查登录状态
if (!isLoggedIn()) {
    header('Location: login.php');
    exit;
}
$id = $_GET['id'] ?? null;
$post = $id ? getPost($id) : null;
// 处理表单提交
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $title = $_POST['title'];
    $content = $_POST['content'];
    $userId = $_SESSION['user_id'];
    if ($id) {
        updatePost($id, $title, $content);
    } else {
        createPost($title, $content, $userId);
    }
    header('Location: dashboard.php');
    exit;
}
?>
<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8"><?php echo $id ? '编辑' : '发布'; ?>文章 - <?php echo SITE_NAME; ?></title>
    <link rel="stylesheet" href="../assets/css/style.css">
</head>
<body>
    <header>
        <h1><?php echo $id ? '编辑' : '发布'; ?>文章</h1>
        <nav>
            <a href="dashboard.php">返回管理首页</a>
        </nav>
    </header>
    <div class="container">
        <form method="POST" action="">
            <div>
                <label>标题:</label>
                <input type="text" name="title" value="<?php echo $post ? e($post['title']) : ''; ?>" required>
            </div>
            <div>
                <label>内容:</label>
                <textarea name="content" rows="15" required><?php echo $post ? e($post['content']) : ''; ?></textarea>
            </div>
            <button type="submit"><?php echo $id ? '保存修改' : '发布文章'; ?></button>
        </form>
    </div>
</body>
</html>

logout.php - 退出登录

<?php
session_start();
session_destroy();
header('Location: login.php');
exit;
?>

样式文件 (style.css)

/* 基础样式 */
* {
    margin: 0;
    padding: 0;
    box-sizing: border-box;
}
body {
    font-family: 'Microsoft YaHei', Arial, sans-serif;
    background: #f5f5f5;
    color: #333;
    line-height: 1.6;
}
header {
    background: #2c3e50;
    color: white;
    padding: 1rem 2rem;
    display: flex;
    justify-content: space-between;
    align-items: center;
}
header h1 {
    font-size: 1.5rem;
}
nav a {
    color: white;
    margin-left: 1rem;
    text-decoration: none;
}
.container {
    max-width: 1200px;
    margin: 2rem auto;
    padding: 0 1rem;
}
/* 文章样式 */
.post {
    background: white;
    padding: 1.5rem;
    margin-bottom: 2rem;
    border-radius: 5px;
    box-shadow: 0 2px 5px rgba(0,0,0,0.1);
}
.post h2 {
    margin-bottom: 1rem;
    color: #2c3e50;
}
.meta {
    color: #666;
    font-size: 0.9rem;
    margin-bottom: 1rem;
}
.meta span {
    margin-right: 1rem;
}
.content {
    margin-bottom: 1rem;
}
.read-more {
    display: inline-block;
    background: #3498db;
    color: white;
    padding: 0.5rem 1rem;
    text-decoration: none;
    border-radius: 3px;
}
/* 后台表格样式 */
table {
    width: 100%;
    background: white;
    border-collapse: collapse;
    box-shadow: 0 2px 5px rgba(0,0,0,0.1);
}
th, td {
    padding: 1rem;
    text-align: left;
    border-bottom: 1px solid #ddd;
}
th {
    background: #f8f9fa;
}
/* 表单样式 */
form {
    background: white;
    padding: 2rem;
    border-radius: 5px;
    box-shadow: 0 2px 5px rgba(0,0,0,0.1);
    max-width: 600px;
    margin: 0 auto;
}
form div {
    margin-bottom: 1rem;
}
label {
    display: block;
    margin-bottom: 0.5rem;
    font-weight: bold;
}
input[type="text"],
input[type="password"],
textarea {
    width: 100%;
    padding: 0.75rem;
    border: 1px solid #ddd;
    border-radius: 3px;
}
button {
    background: #3498db;
    color: white;
    padding: 0.75rem 2rem;
    border: none;
    border-radius: 3px;
    cursor: pointer;
}
button:hover {
    background: #2980b9;
}
/* 响应式设计 */
@media (max-width: 768px) {
    header {
        flex-direction: column;
        text-align: center;
    }
    nav {
        margin-top: 1rem;
    }
}

使用说明

安装步骤:

  1. 创建数据库并导入SQL文件
  2. 配置 includes/config.php 中的数据库连接信息
  3. 创建初始管理员账号
  4. 将文件放置到Web服务器目录

常见扩展功能:

  • 文件上传:在文章编辑中添加图片上传功能
  • 分类管理:添加文章分类
  • 评论功能:添加用户评论
  • 搜索功能:添加文章搜索
  • 分页功能:当文章较多时分页显示

这个系统适合作为学习和入门项目,可以直接使用或根据需求进行扩展。

抱歉,评论功能暂时关闭!