<?php
/**
 * Redirect URL based on DNS TXT record value. Requires A records to be pointed to the server's IP Address and a TXT
 * record with redirection value. Author: Ryan Fitton (https://ryanfitton.co.uk) Version: 1.0.0
 *
 * Examples:
 * example.com.         1800    IN    A    123.45.67.89
 * www.example.com.     1800    IN    A    123.45.67.89
 * example.com.         1800    IN    TXT    "redirect_https://www.google.com"
 * www.example.com.        1800    IN    TXT    "redirect_https://www.google.com"
 */

//The redirect prefix
$prefix   = 'redirect_';
$httpHost = $_SERVER['HTTP_HOST'];

// Check if the HTTP_HOST is a domain
if (filter_var($httpHost, FILTER_VALIDATE_DOMAIN)) {
    //Find the TXT DNS records for this host
    $txts = dns_get_record($httpHost, DNS_TXT);
}

if (isset($txts) && is_array($txts) && $txts) {
    //Loop through each TXT record
    foreach ($txts as $txt) {
        // Check if it's an array before looping through it
        if (!array_key_exists('entries', $txt) || !is_array($txt['entries'])) {
            continue;
        }

        //Loop through each record entry
        foreach ($txt['entries'] as $txtValue) {
            //If the text record includes 'redirect_'
            if (preg_match('/^' . preg_quote($prefix, '/') . '(.*)$/i', $txtValue, $hits)) {
                //Set the 1st key as the URL addrress and Sanitize data
                $url = filter_var($hits[1], FILTER_SANITIZE_URL);

                //Check if URL is valid
                if (filter_var($url, FILTER_VALIDATE_URL)) {
                    //Perform a temporary redirect (302)
                    header('Location: ' . $url, true, 302);
                    exit;

                    //If the URL is not valid
                } else {
                    //Display message on screen
                    echo 'Invalid URL: ' . $url;
                    exit;
                }
            }
        }
    }
}

include 'index.html';
?>
