What are the advantages and disadvantages of using PHP scripts to control access to protected HTML files instead of traditional methods like .htpasswd files?
Using PHP scripts to control access to protected HTML files allows for more flexibility and customization compared to traditional methods like .htpasswd files. With PHP scripts, you can implement user authentication, session management, and role-based access control easily. However, PHP scripts may introduce additional complexity and potential security vulnerabilities if not implemented properly.
<?php
session_start();
$valid_username = 'admin';
$valid_password = 'password';
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
if ($_POST['username'] == $valid_username && $_POST['password'] == $valid_password) {
$_SESSION['authenticated'] = true;
} else {
echo 'Invalid username or password';
}
}
if (!isset($_SESSION['authenticated']) || $_SESSION['authenticated'] !== true) {
header('HTTP/1.1 401 Unauthorized');
echo 'Access denied';
exit;
}
?>