What best practices should be followed when handling user input in PHP to prevent header injection vulnerabilities?

Header injection vulnerabilities can occur when user input is not properly sanitized before being used in functions like header(). To prevent this, it is recommended to use functions like header_remove() to clear any existing headers before setting new ones, and to sanitize user input using functions like strip_tags() or htmlspecialchars(). Additionally, always validate and sanitize user input before using it in header functions to prevent malicious code injection.

// Clear existing headers to prevent header injection
header_remove();

// Sanitize user input before setting new headers
$user_input = strip_tags($_POST['user_input']);
header("Location: /somepage.php?input=" . urlencode($user_input));