What are the best practices for ensuring proper handling of domain-based redirection in PHP scripts?

When handling domain-based redirection in PHP scripts, it is important to ensure proper validation of the input domain and to sanitize it to prevent any security vulnerabilities such as open redirects or injection attacks. One way to do this is by using a whitelist approach where only specific domains are allowed for redirection. Additionally, always sanitize and validate user input before using it in a redirect function to prevent any potential security risks.

// Example of proper handling of domain-based redirection in PHP

$allowed_domains = array('example.com', 'example2.com'); // Define a whitelist of allowed domains

$input_domain = $_GET['domain']; // Get the input domain from user input

// Validate and sanitize the input domain
if (in_array($input_domain, $allowed_domains)) {
    $redirect_url = 'https://' . $input_domain; // Construct the redirect URL
    header('Location: ' . $redirect_url); // Redirect to the specified domain
    exit();
} else {
    echo 'Invalid domain specified'; // Display an error message if the input domain is not allowed
}