php 实现商城图片
PHP 实现商城图片功能
图片上传处理
使用PHP处理文件上传需要配置表单的enctype为multipart/form-data。通过$_FILES全局数组获取上传的文件信息,检查文件类型和大小,确保安全。
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
$targetDir = "uploads/";
$targetFile = $targetDir . basename($_FILES["image"]["name"]);
$imageFileType = strtolower(pathinfo($targetFile, PATHINFO_EXTENSION));
$check = getimagesize($_FILES["image"]["tmp_name"]);
if ($check === false) {
echo "文件不是图片。";
exit;
}
if ($_FILES["image"]["size"] > 500000) {
echo "文件太大。";
exit;
}
$allowedTypes = ["jpg", "png", "jpeg", "gif"];
if (!in_array($imageFileType, $allowedTypes)) {
echo "只允许上传 JPG, JPEG, PNG, GIF 文件。";
exit;
}
if (move_uploaded_file($_FILES["image"]["tmp_name"], $targetFile)) {
echo "文件上传成功。";
} else {
echo "上传失败。";
}
}
图片存储与数据库记录
将上传的图片路径存入数据库,便于后续管理和展示。使用预处理语句防止SQL注入。
$pdo = new PDO("mysql:host=localhost;dbname=shop", "username", "password");
$stmt = $pdo->prepare("INSERT INTO product_images (product_id, image_path) VALUES (:product_id, :image_path)");
$stmt->bindParam(':product_id', $productId);
$stmt->bindParam(':image_path', $targetFile);
$stmt->execute();
图片展示
从数据库读取图片路径并展示在商品页面上。确保路径正确,避免直接暴露服务器文件系统。

$stmt = $pdo->prepare("SELECT image_path FROM product_images WHERE product_id = :product_id");
$stmt->bindParam(':product_id', $productId);
$stmt->execute();
$images = $stmt->fetchAll(PDO::FETCH_ASSOC);
foreach ($images as $image) {
echo '<img src="' . htmlspecialchars($image['image_path']) . '" alt="商品图片">';
}
图片压缩与优化
使用GD库或ImageMagick对上传的图片进行压缩和优化,减少存储空间和加载时间。
function compressImage($source, $destination, $quality) {
$info = getimagesize($source);
if ($info['mime'] == 'image/jpeg') {
$image = imagecreatefromjpeg($source);
} elseif ($info['mime'] == 'image/png') {
$image = imagecreatefrompng($source);
}
imagejpeg($image, $destination, $quality);
imagedestroy($image);
}
compressImage($targetFile, $targetFile, 75);
图片水印添加
为商品图片添加水印,防止盗用。使用GD库在图片上叠加文字或图片水印。

function addWatermark($imagePath, $watermarkText) {
$image = imagecreatefromjpeg($imagePath);
$color = imagecolorallocate($image, 255, 255, 255);
imagettftext($image, 20, 0, 10, 30, $color, "arial.ttf", $watermarkText);
imagejpeg($image, $imagePath);
imagedestroy($image);
}
addWatermark($targetFile, "商城名称");
图片缩略图生成
为商品列表生成缩略图,提升页面加载速度。使用GD库调整图片尺寸。
function createThumbnail($source, $destination, $width, $height) {
$info = getimagesize($source);
if ($info['mime'] == 'image/jpeg') {
$image = imagecreatefromjpeg($source);
} elseif ($info['mime'] == 'image/png') {
$image = imagecreatefrompng($source);
}
$thumbnail = imagecreatetruecolor($width, $height);
imagecopyresized($thumbnail, $image, 0, 0, 0, 0, $width, $height, $info[0], $info[1]);
imagejpeg($thumbnail, $destination);
imagedestroy($image);
imagedestroy($thumbnail);
}
createThumbnail($targetFile, "uploads/thumbnail_" . basename($targetFile), 150, 150);
图片删除功能
提供删除图片的功能,同时从数据库和文件系统中移除相关记录。
function deleteImage($imageId) {
$pdo = new PDO("mysql:host=localhost;dbname=shop", "username", "password");
$stmt = $pdo->prepare("SELECT image_path FROM product_images WHERE id = :id");
$stmt->bindParam(':id', $imageId);
$stmt->execute();
$image = $stmt->fetch(PDO::FETCH_ASSOC);
if (unlink($image['image_path'])) {
$stmt = $pdo->prepare("DELETE FROM product_images WHERE id = :id");
$stmt->bindParam(':id', $imageId);
$stmt->execute();
echo "图片删除成功。";
} else {
echo "删除失败。";
}
}
图片批量处理
对于大量图片上传或处理,使用循环和批量操作提高效率。
foreach ($_FILES['images']['tmp_name'] as $key => $tmpName) {
$targetFile = $targetDir . basename($_FILES['images']['name'][$key]);
if (move_uploaded_file($tmpName, $targetFile)) {
$stmt = $pdo->prepare("INSERT INTO product_images (product_id, image_path) VALUES (:product_id, :image_path)");
$stmt->bindParam(':product_id', $productId);
$stmt->bindParam(':image_path', $targetFile);
$stmt->execute();
}
}






