MINI
C:
/
xampp
/
htdocs
/
cek
/
Upload File:
files >> C:/xampp/htdocs/cek/profile.php
<?php session_start(); include 'db.php'; if (!isset($_SESSION['user_id'])) { header("Location: login.php"); exit(); } $current_user_id = $_SESSION['user_id']; $errors = []; $success = ''; // Get current user data $stmt = $pdo->prepare("SELECT * FROM users WHERE id = ?"); $stmt->execute([$current_user_id]); $user = $stmt->fetch(); // Handle profile update if ($_SERVER['REQUEST_METHOD'] == 'POST') { if (isset($_POST['update_profile'])) { $username = trim($_POST['username']); $current_password = $_POST['current_password']; $new_password = $_POST['new_password']; $confirm_password = $_POST['confirm_password']; // Validate username if (empty($username)) { $errors[] = "Username tidak boleh kosong"; } // Validate password if trying to change if (!empty($new_password)) { if (!password_verify($current_password, $user['password'])) { $errors[] = "Password saat ini salah"; } elseif ($new_password !== $confirm_password) { $errors[] = "Password baru tidak cocok"; } elseif (strlen($new_password) < 6) { $errors[] = "Password minimal 6 karakter"; } } if (empty($errors)) { // Handle profile picture upload $profile_picture = $user['profile_picture']; if ($_FILES['profile_picture']['error'] == UPLOAD_ERR_OK) { $file_name = $_FILES['profile_picture']['name']; $file_tmp = $_FILES['profile_picture']['tmp_name']; $file_size = $_FILES['profile_picture']['size']; $file_type = $_FILES['profile_picture']['type']; // Validate image $allowed_types = ['image/jpeg', 'image/png', 'image/gif']; if (in_array($file_type, $allowed_types) && $file_size <= 2 * 1024 * 1024) { // Max 2MB $ext = pathinfo($file_name, PATHINFO_EXTENSION); $new_filename = 'profile_' . $current_user_id . '_' . time() . '.' . $ext; $upload_path = 'uploads/' . $new_filename; if (move_uploaded_file($file_tmp, $upload_path)) { // Delete old picture if exists if ($profile_picture && file_exists('uploads/' . $profile_picture)) { unlink('uploads/' . $profile_picture); } $profile_picture = $new_filename; } else { $errors[] = "Gagal mengupload foto profil"; } } else { $errors[] = "Format file harus JPG, PNG atau GIF (max 2MB)"; } } // Update user data $data = [':username' => $username]; $password_update = ''; if (!empty($new_password)) { $password_hash = password_hash($new_password, PASSWORD_DEFAULT); $data[':password'] = $password_hash; $password_update = ', password = :password'; } $data[':profile_picture'] = $profile_picture; $data[':id'] = $current_user_id; $stmt = $pdo->prepare("UPDATE users SET username = :username, profile_picture = :profile_picture $password_update WHERE id = :id"); if ($stmt->execute($data)) { $_SESSION['message'] = ['type' => 'success', 'text' => 'Profil berhasil diperbarui!']; header("Location: profile.php"); exit(); } else { $errors[] = "Gagal memperbarui profil"; } } } } ?>
Copyright ©2021 || Defacer Indonesia