How can PHP be used to interact with a .htaccess file for authentication purposes in a forum setting?

To interact with a .htaccess file for authentication purposes in a forum setting using PHP, you can create a login system that prompts users to enter their credentials. Upon successful authentication, PHP can generate the necessary .htpasswd file entries and update the .htaccess file to restrict access to authorized users only.

<?php
$username = $_POST['username'];
$password = $_POST['password'];

$htpasswd_file = '.htpasswd';
$htaccess_file = '.htaccess';

if (file_exists($htpasswd_file)) {
    $htpasswd_content = file_get_contents($htpasswd_file);
} else {
    $htpasswd_content = '';
}

$htpasswd_lines = explode("\n", $htpasswd_content);
$existing_user = false;

foreach ($htpasswd_lines as $line) {
    $credentials = explode(':', $line);
    if ($credentials[0] == $username) {
        $existing_user = true;
        break;
    }
}

if (!$existing_user) {
    $new_line = $username . ':' . password_hash($password, PASSWORD_DEFAULT) . "\n";
    file_put_contents($htpasswd_file, $new_line, FILE_APPEND);

    $htaccess_content = "AuthType Basic\n";
    $htaccess_content .= "AuthName 'Restricted Area'\n";
    $htaccess_content .= "AuthUserFile " . __DIR__ . "/" . $htpasswd_file . "\n";
    $htaccess_content .= "Require valid-user\n";

    file_put_contents($htaccess_file, $htaccess_content);
}

// Redirect to forum page
header('Location: forum.php');
?>