Current directory: /home/klas4s23/domains/585455.klas4s23.mid-ica.nl/public_html/Gastenboek/uploads
<?php
/**
* API Endpoint: User Login
* POST parameters:
* - username: Username or email
* - password: Plain text password
*/
session_start();
header('Content-Type: application/json');
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: POST');
header('Access-Control-Allow-Headers: Content-Type');
header('Access-Control-Allow-Credentials: true');
require_once 'config.php';
if ($_SERVER['REQUEST_METHOD'] === 'OPTIONS') {
http_response_code(200);
exit();
}
if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
http_response_code(405);
echo json_encode(['success' => false, 'error' => 'Method not allowed']);
exit();
}
try {
$input = json_decode(file_get_contents('php://input'), true);
if (json_last_error() !== JSON_ERROR_NONE) {
throw new Exception('Invalid JSON: ' . json_last_error_msg());
}
if (!isset($input['username']) || !isset($input['password'])) {
throw new Exception('Username and password are required');
}
$username = trim($input['username']);
$password = $input['password'];
$pdo = getDbConnection();
// Find user by username or email
$stmt = $pdo->prepare("
SELECT user_id, username, email, password_hash, full_name, is_active
FROM users
WHERE (username = :username OR email = :email) AND is_active = 1
");
$stmt->execute([
':username' => $username,
':email' => $username
]);
$user = $stmt->fetch();
if (!$user) {
throw new Exception('Invalid username or password');
}
// Verify password
if (!password_verify($password, $user['password_hash'])) {
throw new Exception('Invalid username or password');
}
// Update last login
$stmt = $pdo->prepare("UPDATE users SET last_login = CURRENT_TIMESTAMP WHERE user_id = :user_id");
$stmt->execute([':user_id' => $user['user_id']]);
// Set session
$_SESSION['user_id'] = $user['user_id'];
$_SESSION['username'] = $user['username'];
$_SESSION['email'] = $user['email'];
$_SESSION['full_name'] = $user['full_name'];
echo json_encode([
'success' => true,
'message' => 'Login successful',
'user' => [
'user_id' => $user['user_id'],
'username' => $user['username'],
'email' => $user['email'],
'full_name' => $user['full_name']
],
'session_id' => session_id()
]);
} catch (Exception $e) {
http_response_code(401);
echo json_encode([
'success' => false,
'error' => $e->getMessage()
]);
}