How can .htaccess be used to authenticate users against a MySQL database in PHP?

To authenticate users against a MySQL database in PHP using .htaccess, you can create a PHP script that checks the user's credentials against the database and returns a response based on the authentication result. You can then use mod_rewrite in the .htaccess file to redirect requests to this PHP script for authentication.

<?php
// Connect to MySQL database
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "database_name";

$conn = new mysqli($servername, $username, $password, $dbname);

// Check connection
if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
}

// Check user credentials
$username = $_SERVER['PHP_AUTH_USER'];
$password = $_SERVER['PHP_AUTH_PW'];

$sql = "SELECT * FROM users WHERE username='$username' AND password='$password'";
$result = $conn->query($sql);

if ($result->num_rows > 0) {
    // User authenticated
    echo "Authorized";
} else {
    // User not authenticated
    header('HTTP/1.1 401 Unauthorized');
    echo "Unauthorized";
}

$conn->close();
?>