php怎么实现图文
PHP实现图文上传与展示
表单设计
创建一个包含文件上传和文本输入的表单,确保表单的enctype属性设置为multipart/form-data,这是文件上传的必要条件。
<form action="upload.php" method="post" enctype="multipart/form-data">
<input type="text" name="title" placeholder="输入标题">
<textarea name="content" placeholder="输入内容"></textarea>
<input type="file" name="image">
<input type="submit" value="提交">
</form>
文件上传处理 在服务器端使用PHP处理上传的文件,检查文件类型、大小,并将文件移动到指定目录。
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
$title = $_POST['title'];
$content = $_POST['content'];
$image = $_FILES['image'];
$allowedTypes = ['image/jpeg', 'image/png', 'image/gif'];
$maxSize = 2 * 1024 * 1024; // 2MB
if (in_array($image['type'], $allowedTypes) && $image['size'] <= $maxSize) {
$uploadPath = 'uploads/' . basename($image['name']);
move_uploaded_file($image['tmp_name'], $uploadPath);
}
}
数据库存储 将文本内容和图片路径存储到数据库中,方便后续查询和展示。

$db = new PDO('mysql:host=localhost;dbname=test', 'username', 'password');
$stmt = $db->prepare("INSERT INTO posts (title, content, image_path) VALUES (?, ?, ?)");
$stmt->execute([$title, $content, $uploadPath]);
图文展示 从数据库查询数据并在页面上展示图文内容。
$stmt = $db->query("SELECT * FROM posts ORDER BY id DESC");
while ($post = $stmt->fetch()) {
echo "<h3>{$post['title']}</h3>";
echo "<p>{$post['content']}</p>";
echo "<img src='{$post['image_path']}' alt='{$post['title']}'>";
}
安全注意事项 对用户输入进行过滤和验证,防止SQL注入和XSS攻击。

$title = htmlspecialchars($_POST['title']);
$content = htmlspecialchars($_POST['content']);
图片处理 使用GD库或Imagick对上传的图片进行压缩或生成缩略图,优化页面加载速度。
$sourceImage = imagecreatefromjpeg($uploadPath);
$thumbnail = imagescale($sourceImage, 200);
imagejpeg($thumbnail, 'uploads/thumb_' . basename($image['name']));
响应式展示 使用CSS确保图片在不同设备上都能正确显示。
img {
max-width: 100%;
height: auto;
}






