phpcms
是一个基于 PHP 的内容管理系统(CMS),它允许用户轻松地创建、编辑和管理网站内容。在 phpcms
中添加评论图片功能,通常涉及到以下几个基础概念:
以下是一个简单的示例代码,展示如何在 phpcms
中实现评论添加图片功能:
<form action="submit_comment.php" method="post" enctype="multipart/form-data">
<textarea name="comment" placeholder="请输入评论"></textarea>
<input type="file" name="image[]" multiple>
<input type="submit" value="提交评论">
</form>
<?php
// submit_comment.php
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
$comment = $_POST['comment'];
$images = $_FILES['image'];
// 连接数据库
$db = new PDO('mysql:host=localhost;dbname=phpcms', 'username', 'password');
// 插入评论
$stmt = $db->prepare("INSERT INTO comments (comment) VALUES (:comment)");
$stmt->bindParam(':comment', $comment);
$stmt->execute();
$comment_id = $db->lastInsertId();
// 处理图片上传
foreach ($images['name'] as $key => $value) {
if ($images['error'][$key] === UPLOAD_ERR_OK) {
$file_name = $images['name'][$key];
$file_tmp = $images['tmp_name'][$key];
$file_size = $images['size'][$key];
$file_type = $images['type'][$key];
// 移动文件到指定目录
$upload_dir = 'uploads/';
if (!file_exists($upload_dir)) {
mkdir($upload_dir, 0777, true);
}
$file_path = $upload_dir . $file_name;
move_uploaded_file($file_tmp, $file_path);
// 插入图片信息到数据库
$stmt = $db->prepare("INSERT INTO comment_images (comment_id, file_path) VALUES (:comment_id, :file_path)");
$stmt->bindParam(':comment_id', $comment_id);
$stmt->bindParam(':file_path', $file_path);
$stmt->execute();
}
}
echo '评论提交成功!';
}
?>
<?php
// display_comments.php
$db = new PDO('mysql:host=localhost;dbname=phpcms', 'username', 'password');
$stmt = $db->query("SELECT * FROM comments");
$comments = $stmt->fetchAll(PDO::FETCH_ASSOC);
foreach ($comments as $comment) {
echo '<div class="comment">';
echo '<p>' . htmlspecialchars($comment['comment']) . '</p>';
$stmt = $db->prepare("SELECT * FROM comment_images WHERE comment_id = :comment_id");
$stmt->bindParam(':comment_id', $comment['id']);
$stmt->execute();
$images = $stmt->fetchAll(PDO::FETCH_ASSOC);
foreach ($images as $image) {
echo '<img src="' . htmlspecialchars($image['file_path']) . '" alt="评论图片">';
}
echo '</div>';
}
?>
php.ini
中的 upload_max_filesize
和 post_max_size
设置,确保它们足够大。jpg
、png
)。希望以上信息对你有所帮助!
领取专属 10元无门槛券
手把手带您无忧上云