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();
?>
Related Questions
- What are the advantages of passing variables as parameters to functions in PHP instead of using global variables?
- What best practices should be followed when handling form submissions and email sending functionality in PHP scripts to avoid errors and improve user experience?
- Are there any security considerations when using PHP to directly interact with hardware devices like a COM port?