What potential security risks are present in the provided PHP code?
The provided PHP code is vulnerable to SQL injection attacks due to the use of unsanitized user input in the SQL query. To mitigate this risk, we should use prepared statements with parameterized queries to prevent malicious SQL injection attempts.
// Original vulnerable code
$user_input = $_POST['username'];
$query = "SELECT * FROM users WHERE username = '$user_input'";
$result = mysqli_query($conn, $query);
// Fixed code using prepared statements
$user_input = $_POST['username'];
$query = "SELECT * FROM users WHERE username = ?";
$stmt = $conn->prepare($query);
$stmt->bind_param("s", $user_input);
$stmt->execute();
$result = $stmt->get_result();
Related Questions
- What are the potential pitfalls of manually sorting or grouping arrays in PHP, and how can they be avoided?
- What are some best practices for using PHP to generate and manipulate HTML files with user input?
- In PHP, why is it important to specify the character set in functions like htmlentities to avoid default settings that may change in future versions?