What are the best practices for handling user input in PHP to avoid security vulnerabilities like SQL injection?

To avoid security vulnerabilities like SQL injection in PHP, it is essential to properly sanitize and validate user input before using it in database queries. One way to achieve this is by using prepared statements with parameterized queries, which separate the SQL query logic from the user input data. This approach helps prevent malicious SQL code from being executed by treating user input as data rather than executable code.

// Establish a database connection
$pdo = new PDO('mysql:host=localhost;dbname=mydatabase', 'username', 'password');

// Sanitize and validate user input
$userInput = $_POST['input'];
$filteredInput = filter_var($userInput, FILTER_SANITIZE_STRING);

// Prepare a SQL query using a prepared statement
$stmt = $pdo->prepare("SELECT * FROM users WHERE username = :username");
$stmt->bindParam(':username', $filteredInput, PDO::PARAM_STR);
$stmt->execute();

// Fetch the results
$results = $stmt->fetchAll(PDO::FETCH_ASSOC);