How can PHP interact with a MySQL database to manage user access without using .htpasswd files?

To manage user access without using .htpasswd files, PHP can interact with a MySQL database by storing user credentials (such as username and password) in a database table. When a user tries to log in, PHP can query the database to verify the credentials. If the credentials match, the user is granted access.

// Establish a connection to the MySQL database
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "database";

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

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

// Retrieve user credentials from a form submission
$username = $_POST['username'];
$password = $_POST['password'];

// Query the database to check if the user exists
$sql = "SELECT * FROM users WHERE username='$username' AND password='$password'";
$result = $conn->query($sql);

if ($result->num_rows > 0) {
    // User exists, grant access
    echo "Access granted!";
} else {
    // User does not exist, deny access
    echo "Access denied!";
}

// Close the database connection
$conn->close();