73 lines
2.2 KiB
PHP
73 lines
2.2 KiB
PHP
<?php
|
|
$rootPath = dirname(dirname(dirname(__DIR__)));
|
|
require_once($rootPath . '/src/config/env.php');
|
|
require_once($rootPath . '/src/config/session.php');
|
|
require_once($rootPath . '/src/config/connection.php');
|
|
require_once($rootPath . '/src/config/functions.php');
|
|
|
|
$response = array('status' => 'error', 'message' => 'Something went wrong');
|
|
|
|
// Check if the user is logged in
|
|
if (!isset($_SESSION['user_id'])) {
|
|
$response['message'] = 'You are not logged in.';
|
|
echo json_encode($response);
|
|
exit();
|
|
}
|
|
|
|
$user_id = $_SESSION['user_id'];
|
|
|
|
// Check if form data is submitted
|
|
if (isset($_POST['current_password'], $_POST['new_password'], $_POST['confirm_password'])) {
|
|
$current_password = $_POST['current_password'];
|
|
$new_password = $_POST['new_password'];
|
|
$confirm_password = $_POST['confirm_password'];
|
|
|
|
// Validate new passwords
|
|
if ($new_password !== $confirm_password) {
|
|
$response['message'] = 'New passwords do not match.';
|
|
echo json_encode($response);
|
|
exit();
|
|
}
|
|
|
|
// Fetch the stored hashed password from the database
|
|
$sql = "SELECT password FROM users WHERE user_id = ?";
|
|
$stmt = $conn->prepare($sql);
|
|
$stmt->bind_param("i", $user_id);
|
|
$stmt->execute();
|
|
$result = $stmt->get_result();
|
|
$user = $result->fetch_assoc();
|
|
|
|
if (!$user) {
|
|
$response['message'] = 'User not found.';
|
|
echo json_encode($response);
|
|
exit();
|
|
}
|
|
|
|
// Verify the current password
|
|
if (!password_verify($current_password, $user['password'])) {
|
|
$response['message'] = 'Current password is incorrect.';
|
|
echo json_encode($response);
|
|
exit();
|
|
}
|
|
|
|
// Hash the new password
|
|
$new_password_hash = password_hash($new_password, PASSWORD_BCRYPT);
|
|
|
|
// Update the new password in the database
|
|
$sql = "UPDATE users SET password = ? WHERE user_id = ?";
|
|
$stmt = $conn->prepare($sql);
|
|
$stmt->bind_param("si", $new_password_hash, $user_id);
|
|
|
|
if ($stmt->execute()) {
|
|
$response['status'] = 'success';
|
|
$response['message'] = 'Password changed successfully.';
|
|
} else {
|
|
$response['message'] = 'Failed to change password.';
|
|
}
|
|
} else {
|
|
$response['message'] = 'Invalid form submission.';
|
|
}
|
|
|
|
echo json_encode($response);
|
|
?>
|