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();
Keywords
Related Questions
- How can the use of static variables in PHP classes impact the functionality of the code, as seen in the forum thread?
- How can you ensure that previously selected checkbox values are displayed when reloading a form in PHP?
- How can you calculate the difference in days between two date variables in PHP?