What are the best practices for handling user authentication and access control in PHP scripts without using a database or CMS?
User authentication and access control can be implemented in PHP scripts without using a database or CMS by storing user credentials securely in a PHP file and using session variables to track authenticated users. Access control can be managed by checking user roles or permissions before allowing access to specific resources.
<?php
session_start();
$users = [
'admin' => [
'password' => 'password123',
'role' => 'admin'
],
'user' => [
'password' => '123password',
'role' => 'user'
]
];
function authenticateUser($username, $password) {
global $users;
if (isset($users[$username]) && $users[$username]['password'] === $password) {
$_SESSION['user'] = $users[$username];
return true;
}
return false;
}
function checkRole($role) {
if (isset($_SESSION['user']) && $_SESSION['user']['role'] === $role) {
return true;
}
return false;
}
// Example usage
if (authenticateUser('admin', 'password123')) {
echo 'User authenticated as admin';
} else {
echo 'Authentication failed';
}
if (checkRole('admin')) {
echo 'User has admin role';
} else {
echo 'User does not have admin role';
}
?>