What are the best practices for handling user input and redirecting in PHP to maintain security and prevent vulnerabilities like SQL injections?

To handle user input securely and prevent vulnerabilities like SQL injections in PHP, it is crucial to sanitize and validate all user input before using it in SQL queries. Additionally, always use prepared statements or parameterized queries to interact with the database to prevent SQL injection attacks.

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

// Connect to the database
$pdo = new PDO('mysql:host=localhost;dbname=my_database', 'username', 'password');

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

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

// Redirect user after processing the input
header('Location: success.php');
exit();