Google Login with Google

Delete Image in PHP (Step-by-Step)

📌 Delete Image in PHP (Step-by-Step)

When you upload images,
you also need a way to delete them.

Important:
👉 You must delete BOTH:

file (server)
database record
1️⃣ Add delete button

Inside gallery.php:

<a href="delete.php?id=<?= $row['id'] ?>" onclick="return confirm('Delete this image?')">
Delete
</a>
2️⃣ Create delete.php
/hosting/foliocraft/html/delete.php
3️⃣ Delete logic (VERY IMPORTANT)
<?php

require_once 'db.php';

if (isset($_GET['id'])) {

$id = $_GET['id'];

// 1. Get file path from DB
$stmt = $conn->prepare("SELECT image_url FROM gallery WHERE id=?");
$stmt->bind_param("i", $id);
$stmt->execute();
$result = $stmt->get_result();
$row = $result->fetch_assoc();

if ($row) {

$filePath = $row['image_url'];

// 2. Delete file from server
if (file_exists($filePath)) {
unlink($filePath);
}

// 3. Delete DB record
$stmt = $conn->prepare("DELETE FROM gallery WHERE id=?");
$stmt->bind_param("i", $id);
$stmt->execute();

echo "Deleted successfully.";

} else {
echo "Image not found.";
}
}
?>
🔥 핵심 포인트
DB만 삭제 ❌ → 파일 남음 (용량 낭비)
파일만 삭제 ❌ → DB 깨짐

👉 반드시 둘 다 삭제해야 함

🔐 Security Tip
로그인 사용자만 삭제 가능하게 제한
auth.php 체크 추가
GET 대신 POST 사용 추천 (더 안전)
✅ Summary

To delete image properly:

Get file path
Delete file (unlink)
Delete DB record
← Back to list
💬 Comments (0)