How can the code be modified to implement a more robust and scalable user authentication system, considering the current structure and logic?
The code can be modified to implement a more robust and scalable user authentication system by incorporating features such as password hashing, salting, and using prepared statements to prevent SQL injection attacks. Additionally, implementing session management and secure cookie handling can enhance the security of the authentication system.
<?php
// Start a session
session_start();
// Database connection
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "database";
$conn = new mysqli($servername, $username, $password, $dbname);
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
// User authentication function
function authenticateUser($username, $password) {
global $conn;
$stmt = $conn->prepare("SELECT id, username, password FROM users WHERE username = ?");
$stmt->bind_param("s", $username);
$stmt->execute();
$result = $stmt->get_result();
if ($result->num_rows == 1) {
$user = $result->fetch_assoc();
if (password_verify($password, $user['password'])) {
$_SESSION['user_id'] = $user['id'];
return true;
}
}
return false;
}
// Logout function
function logoutUser() {
session_unset();
session_destroy();
}
?>
Keywords
Related Questions
- What are the advantages and disadvantages of using functions like strpos and strrchr in PHP for string manipulation tasks?
- What are the potential drawbacks or pitfalls of not implementing pagination in PHP when dealing with a large number of database records?
- What are some best practices for implementing getters and setters in PHP OOP to avoid issues like the one described in the forum thread?