What are the potential security risks associated with using automatic redirection in PHP?

The potential security risks associated with using automatic redirection in PHP include open redirect vulnerabilities, where an attacker can manipulate the redirection URL to redirect users to malicious websites. To mitigate this risk, always validate and sanitize user input before using it in a redirection function.

// Validate and sanitize the redirection URL before using it
$redirect_url = filter_var($_GET['redirect'], FILTER_SANITIZE_URL);

// Perform the redirection only if the URL is valid
if (filter_var($redirect_url, FILTER_VALIDATE_URL)) {
    header("Location: " . $redirect_url);
    exit();
} else {
    // Redirect to a safe location if the URL is invalid
    header("Location: safe_page.php");
    exit();
}