What are the potential pitfalls of automatically redirecting to a URL stored in a config file in PHP?

Automatically redirecting to a URL stored in a config file in PHP can be risky as it opens up the possibility of an attacker modifying the config file to redirect users to malicious websites. To mitigate this risk, it is important to validate the URL before redirecting to ensure it is a trusted and safe destination.

// Example of validating the URL before redirecting
$config = include 'config.php';

$redirectUrl = $config['redirect_url'];

// Validate the URL before redirecting
if (filter_var($redirectUrl, FILTER_VALIDATE_URL)) {
    header("Location: $redirectUrl");
    exit();
} else {
    // Handle invalid URL
    echo "Invalid redirect URL";
}