In the revised PHP code provided, what improvements were made in terms of database interaction and session management compared to the original code?
Issue: The original PHP code had security vulnerabilities due to directly inserting user input into SQL queries, making it susceptible to SQL injection attacks. Additionally, the session management was not secure as it did not use proper session handling functions. Improvements in the revised PHP code: 1. Utilizing prepared statements with parameter binding for secure database interaction. 2. Implementing session_start() at the beginning of the code for proper session management. 3. Using session_regenerate_id() to prevent session fixation attacks. Revised PHP code:
<?php
session_start();
require_once('db_connection.php');
if ($_SERVER["REQUEST_METHOD"] == "POST") {
$username = $_POST['username'];
$password = $_POST['password'];
$stmt = $conn->prepare("SELECT * FROM users WHERE username = ?");
$stmt->bind_param("s", $username);
$stmt->execute();
$result = $stmt->get_result();
if ($result->num_rows == 1) {
$row = $result->fetch_assoc();
if (password_verify($password, $row['password'])) {
$_SESSION['username'] = $username;
session_regenerate_id();
header("Location: dashboard.php");
exit();
} else {
echo "Invalid username or password.";
}
} else {
echo "Invalid username or password.";
}
$stmt->close();
}
$conn->close();
?>
Related Questions
- What potential error could occur when using the mysql_num_rows function in PHP?
- What are the potential consequences of not properly converting special characters in PHP?
- What are some common errors or challenges when extracting city and country information in different languages from GeoIP data in PHP?