<?php
// Start session and include database connection
session_start();
$pdo = new PDO('mysql:host=localhost;dbname=test', 'username', 'password');
// User registration
function register($username, $password) {
global $pdo;
$hashedPassword = password_hash($password, PASSWORD_DEFAULT);
$stmt = $pdo->prepare("INSERT INTO users (username, password) VALUES (?, ?)");
return $stmt->execute([$username, $hashedPassword]);
}
// User login
function login($username, $password) {
global $pdo;
$stmt = $pdo->prepare("SELECT * FROM users WHERE username = ?");
$stmt->execute([$username]);
$user = $stmt->fetch();
if ($user && password_verify($password, $user['password'])) {
$_SESSION['user_id'] = $user['id'];
return true;
}
return false;
}
// Check if user is logged in
function isLoggedIn() {
return isset($_SESSION['user_id']);
}
// Authorization check
function isAdmin() {
global $pdo;
if (!isLoggedIn()) return false;
$stmt = $pdo->prepare("SELECT role FROM users WHERE id = ?");
$stmt->execute([$_SESSION['user_id']]);
$user = $stmt->fetch();
return $user['role'] === 'admin';
}
// Example usage
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
if (isset($_POST['register'])) {
register($_POST['username'], $_POST['password']);
} elseif (isset($_POST['login'])) {
if (login($_POST['username'], $_POST['password'])) {
echo "Logged in successfully.";
} else {
echo "Login failed.";
}
}
}
?>
How do I avoid rehashing overhead with std::set in multithreaded code?
How do I find elements with custom comparators with std::set for embedded targets?
How do I erase elements while iterating with std::set for embedded targets?
How do I provide stable iteration order with std::unordered_map for large datasets?
How do I reserve capacity ahead of time with std::unordered_map for large datasets?
How do I erase elements while iterating with std::unordered_map in multithreaded code?
How do I provide stable iteration order with std::map for embedded targets?
How do I provide stable iteration order with std::map in multithreaded code?
How do I avoid rehashing overhead with std::map in performance-sensitive code?
How do I merge two containers efficiently with std::map for embedded targets?