What are the best practices for sanitizing user input in PHP to prevent SQL injection and other security vulnerabilities?
To prevent SQL injection and other security vulnerabilities, it is important to sanitize user input before using it in database queries. One common method is to use prepared statements with parameterized queries, which separate the SQL query from the user input. Additionally, you can use functions like mysqli_real_escape_string() to escape special characters in user input before using it in a query.
// Establish a database connection
$mysqli = new mysqli("localhost", "username", "password", "database");
// Sanitize user input using mysqli_real_escape_string
$username = $mysqli->real_escape_string($_POST['username']);
$password = $mysqli->real_escape_string($_POST['password']);
// Prepare a SQL query using a parameterized statement
$stmt = $mysqli->prepare("SELECT * FROM users WHERE username = ? AND password = ?");
$stmt->bind_param("ss", $username, $password);
// Execute the query
$stmt->execute();
// Process the results
$result = $stmt->get_result();
while ($row = $result->fetch_assoc()) {
// Do something with the results
}
// Close the statement and connection
$stmt->close();
$mysqli->close();