What are the best practices for handling user input in PHP to prevent injections?
To prevent SQL injections in PHP, it is crucial to sanitize and validate user input before using it in database queries. One common method is to use prepared statements with parameterized queries to ensure that user input is treated as data rather than executable code. Additionally, using functions like mysqli_real_escape_string() can help sanitize input to prevent malicious code injection.
// Establish 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 SQL query using parameterized statements
$stmt = $mysqli->prepare("SELECT * FROM users WHERE username = ? AND password = ?");
$stmt->bind_param("ss", $username, $password);
$stmt->execute();
// Process the query result
$result = $stmt->get_result();
while ($row = $result->fetch_assoc()) {
// Handle the retrieved data
}
// Close the statement and database connection
$stmt->close();
$mysqli->close();