Files
d1041231004-webgis-povertymap/upload.php
T
2026-06-10 20:22:46 +07:00

125 lines
4.8 KiB
PHP

<?php
// upload.php — Handler upload foto rumah & kartu keluarga
header("Content-Type: application/json");
header("Access-Control-Allow-Origin: *");
header("Access-Control-Allow-Methods: POST, OPTIONS");
header("Access-Control-Allow-Headers: Content-Type");
if ($_SERVER['REQUEST_METHOD'] === 'OPTIONS') { http_response_code(200); exit(); }
if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
http_response_code(405);
echo json_encode(["success" => false, "message" => "Hanya menerima POST"]);
exit();
}
// ── KONFIGURASI ──────────────────────────────────────────────
$uploadDir = __DIR__ . '/uploads/';
$uploadUrl = 'http://localhost/web_gis/01/uploads/';
$maxSize = 5 * 1024 * 1024; // 5 MB
$allowedExt = ['jpg', 'jpeg', 'png', 'webp'];
// Buat folder uploads jika belum ada
if (!is_dir($uploadDir)) {
mkdir($uploadDir, 0755, true);
}
// ── VALIDASI ─────────────────────────────────────────────────
$type = $_POST['type'] ?? ''; // 'rumah' atau 'kk'
if (!in_array($type, ['rumah', 'kk'])) {
http_response_code(400);
echo json_encode(["success" => false, "message" => "Parameter 'type' harus 'rumah' atau 'kk'"]);
exit();
}
$idMiskin = (int)($_POST['id_miskin'] ?? 0);
if ($idMiskin <= 0) {
http_response_code(400);
echo json_encode(["success" => false, "message" => "Parameter 'id_miskin' tidak valid"]);
exit();
}
if (empty($_FILES['foto']) || $_FILES['foto']['error'] !== UPLOAD_ERR_OK) {
$errMsg = [
UPLOAD_ERR_INI_SIZE => 'File terlalu besar (melebihi batas php.ini)',
UPLOAD_ERR_FORM_SIZE => 'File terlalu besar',
UPLOAD_ERR_PARTIAL => 'Upload tidak lengkap',
UPLOAD_ERR_NO_FILE => 'Tidak ada file yang diupload',
UPLOAD_ERR_NO_TMP_DIR => 'Folder temporary tidak ditemukan',
UPLOAD_ERR_CANT_WRITE => 'Gagal menulis file',
];
$code = $_FILES['foto']['error'] ?? UPLOAD_ERR_NO_FILE;
echo json_encode(["success" => false, "message" => $errMsg[$code] ?? 'Error upload tidak dikenal']);
exit();
}
// Validasi ukuran
if ($_FILES['foto']['size'] > $maxSize) {
echo json_encode(["success" => false, "message" => "Ukuran file maksimal 5 MB"]);
exit();
}
// Validasi ekstensi
$ext = strtolower(pathinfo($_FILES['foto']['name'], PATHINFO_EXTENSION));
if (!in_array($ext, $allowedExt)) {
echo json_encode(["success" => false, "message" => "Format file harus JPG, PNG, atau WebP"]);
exit();
}
// Validasi MIME type (keamanan tambahan)
$finfo = finfo_open(FILEINFO_MIME_TYPE);
$mimeType = finfo_file($finfo, $_FILES['foto']['tmp_name']);
finfo_close($finfo);
$allowedMime = ['image/jpeg', 'image/png', 'image/webp'];
if (!in_array($mimeType, $allowedMime)) {
echo json_encode(["success" => false, "message" => "Tipe file tidak valid"]);
exit();
}
// ── SIMPAN FILE ──────────────────────────────────────────────
// Nama file: miskin_{id}_{type}_{timestamp}.{ext}
$filename = "miskin_{$idMiskin}_{$type}_" . time() . ".{$ext}";
$destPath = $uploadDir . $filename;
if (!move_uploaded_file($_FILES['foto']['tmp_name'], $destPath)) {
echo json_encode(["success" => false, "message" => "Gagal menyimpan file"]);
exit();
}
// ── UPDATE DATABASE ──────────────────────────────────────────
$host = "localhost";
$dbname = "webgis_spbu";
$username = "root";
$password = "";
try {
$pdo = new PDO("mysql:host=$host;dbname=$dbname;charset=utf8mb4", $username, $password);
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
// Ambil foto lama untuk dihapus
$s = $pdo->prepare("SELECT foto_rumah, foto_kk FROM penduduk_miskin WHERE id=?");
$s->execute([$idMiskin]);
$row = $s->fetch(PDO::FETCH_ASSOC);
$col = $type === 'rumah' ? 'foto_rumah' : 'foto_kk';
// Hapus file lama jika ada
if ($row && !empty($row[$col])) {
$oldFile = $uploadDir . basename($row[$col]);
if (file_exists($oldFile)) unlink($oldFile);
}
// Simpan path baru ke DB
$pdo->prepare("UPDATE penduduk_miskin SET {$col}=? WHERE id=?")->execute([$filename, $idMiskin]);
echo json_encode([
"success" => true,
"message" => "Foto berhasil diupload",
"filename" => $filename,
"url" => $uploadUrl . $filename,
]);
} catch (PDOException $e) {
// File sudah tersimpan tapi DB gagal — hapus file
if (file_exists($destPath)) unlink($destPath);
echo json_encode(["success" => false, "message" => "DB error: " . $e->getMessage()]);
}
?>