What are the recommended methods for validating user input and preventing injection attacks when handling session and cookie data in PHP?

When handling session and cookie data in PHP, it is important to validate user input and prevent injection attacks to ensure the security of your application. One way to do this is by using functions like filter_input() to sanitize and validate user input before using it in your code. Additionally, you can use prepared statements when interacting with databases to prevent SQL injection attacks.

// Validate and sanitize user input for session data
$username = filter_input(INPUT_POST, 'username', FILTER_SANITIZE_STRING);
$password = filter_input(INPUT_POST, 'password', FILTER_SANITIZE_STRING);

// Prevent SQL injection with prepared statements
$stmt = $pdo->prepare("SELECT * FROM users WHERE username = :username AND password = :password");
$stmt->bindParam(':username', $username);
$stmt->bindParam(':password', $password);
$stmt->execute();