What best practices should be followed when using PHP variables in header(Location) functions for redirects?

When using PHP variables in header(Location) functions for redirects, it is important to properly sanitize and validate the input to prevent any potential security vulnerabilities such as header injection attacks. One way to do this is to use the urlencode() function to encode the variables before passing them in the header function.

// Sanitize and validate the input variable
$redirect_url = urlencode($redirect_url);

// Redirect to the specified URL
header("Location: $redirect_url");
exit();