What are common methods to password protect a directory in PHP and how can it be accessed using PHP scripts?
To password protect a directory in PHP, you can use a combination of .htaccess and .htpasswd files. This method involves creating a .htaccess file in the directory you want to protect and specifying the location of a .htpasswd file that stores the usernames and passwords. You can then use PHP scripts to authenticate users against the credentials stored in the .htpasswd file.
<?php
// Check if user is authenticated
if (!isset($_SERVER['PHP_AUTH_USER']) || !isset($_SERVER['PHP_AUTH_PW'])) {
header('WWW-Authenticate: Basic realm="Restricted Area"');
header('HTTP/1.0 401 Unauthorized');
echo 'Authorization Required';
exit;
} else {
$username = $_SERVER['PHP_AUTH_USER'];
$password = $_SERVER['PHP_AUTH_PW'];
// Validate credentials against .htpasswd file
$htpasswd_file = '/path/to/.htpasswd';
$htpasswd_contents = file_get_contents($htpasswd_file);
$valid_credentials = false;
foreach (explode("\n", $htpasswd_contents) as $line) {
list($stored_username, $stored_password) = explode(':', $line);
if ($username == $stored_username && password_verify($password, trim($stored_password))) {
$valid_credentials = true;
break;
}
}
if (!$valid_credentials) {
header('WWW-Authenticate: Basic realm="Restricted Area"');
header('HTTP/1.0 401 Unauthorized');
echo 'Authorization Required';
exit;
}
}
?>