What are the best practices for handling user input and database queries in PHP to prevent header-related issues?

When handling user input and database queries in PHP, it is important to sanitize user input to prevent header injection attacks. One common method is to use prepared statements when interacting with a database to prevent SQL injection attacks. Additionally, always validate and sanitize user input before using it in header functions to prevent header injection vulnerabilities.

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

// Prepare a SQL statement using prepared statements
$stmt = $pdo->prepare("SELECT * FROM users WHERE username = ?");
$stmt->execute([$userInput]);

// Validate and sanitize user input before using it in header functions
$cleanInput = filter_var($userInput, FILTER_SANITIZE_STRING);
header("Location: /success.php?input=" . urlencode($cleanInput));