php实现发布文章
实现文章发布功能
创建数据库表结构
在MySQL中创建一个articles表用于存储文章数据:
CREATE TABLE `articles` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`title` varchar(255) NOT NULL,
`content` text NOT NULL,
`author` varchar(100) NOT NULL,
`created_at` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
创建发布表单
设计一个HTML表单用于提交文章内容:

<form action="publish.php" method="post">
<div>
<label for="title">标题:</label>
<input type="text" id="title" name="title" required>
</div>
<div>
<label for="content">内容:</label>
<textarea id="content" name="content" rows="10" required></textarea>
</div>
<div>
<label for="author">作者:</label>
<input type="text" id="author" name="author" required>
</div>
<button type="submit">发布文章</button>
</form>
处理表单提交
创建publish.php文件处理表单提交:
<?php
// 数据库连接配置
$host = 'localhost';
$dbname = 'your_database';
$username = 'your_username';
$password = 'your_password';
try {
$pdo = new PDO("mysql:host=$host;dbname=$dbname", $username, $password);
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
$title = htmlspecialchars($_POST['title']);
$content = htmlspecialchars($_POST['content']);
$author = htmlspecialchars($_POST['author']);
$stmt = $pdo->prepare("INSERT INTO articles (title, content, author) VALUES (:title, :content, :author)");
$stmt->bindParam(':title', $title);
$stmt->bindParam(':content', $content);
$stmt->bindParam(':author', $author);
$stmt->execute();
header('Location: success.php');
exit;
}
} catch(PDOException $e) {
die("数据库连接失败: " . $e->getMessage());
}
?>
安全增强措施
添加CSRF防护和输入验证:

// 在表单顶部添加CSRF令牌
session_start();
if (empty($_SESSION['csrf_token'])) {
$_SESSION['csrf_token'] = bin2hex(random_bytes(32));
}
<input type="hidden" name="csrf_token" value="<?php echo $_SESSION['csrf_token']; ?>">
// 在publish.php中添加CSRF验证
if (!isset($_POST['csrf_token']) || $_POST['csrf_token'] !== $_SESSION['csrf_token']) {
die('CSRF验证失败');
}
文件上传支持
如需支持图片上传,可以添加文件上传功能:
if (isset($_FILES['image']) && $_FILES['image']['error'] === UPLOAD_ERR_OK) {
$uploadDir = 'uploads/';
$fileName = uniqid() . '_' . basename($_FILES['image']['name']);
$uploadFile = $uploadDir . $fileName;
if (move_uploaded_file($_FILES['image']['tmp_name'], $uploadFile)) {
// 将文件路径保存到数据库
$imagePath = $uploadFile;
}
}
显示发布结果
创建success.php显示发布成功信息:
<?php
session_start();
?>
<!DOCTYPE html>
<html>
<head>
<title>发布成功</title>
</head>
<body>
<h1>文章发布成功</h1>
<p>您的文章已成功发布。</p>
<a href="index.php">返回首页</a>
</body>
</html>






