What potential pitfalls should be considered when using header("Location: ...") in PHP for redirection purposes?
One potential pitfall when using `header("Location: ...")` for redirection in PHP is the risk of header injection attacks. To prevent this, always ensure that the URL being passed to `header("Location: ...")` is properly sanitized and validated. Additionally, make sure to call `exit()` or `die()` immediately after setting the location header to prevent any further code execution.
// Example of secure redirection using header("Location: ...")
$redirect_url = "https://www.example.com";
// Validate and sanitize the URL
if (filter_var($redirect_url, FILTER_VALIDATE_URL)) {
// Set the location header and exit
header("Location: " . $redirect_url);
exit();
} else {
// Handle invalid URL
echo "Invalid URL";
}