How can the Public Suffix List be used to determine valid subdomains in PHP?

The Public Suffix List can be used in PHP to determine valid subdomains by checking if a given domain or subdomain is a public suffix. This can help prevent security vulnerabilities such as cookie injection attacks. By comparing the domain or subdomain against the entries in the Public Suffix List, we can ensure that only valid subdomains are accepted.

// Load the Public Suffix List
$publicSuffixList = file_get_contents('https://publicsuffix.org/list/public_suffix_list.dat');
$publicSuffixes = explode("\n", $publicSuffixList);

// Function to check if a subdomain is valid
function isValidSubdomain($subdomain) {
    global $publicSuffixes;
    
    $subdomainParts = explode('.', $subdomain);
    $subdomainPartsCount = count($subdomainParts);
    
    for ($i = 0; $i < $subdomainPartsCount; $i++) {
        $checkSubdomain = implode('.', array_slice($subdomainParts, $i));
        
        if (in_array($checkSubdomain, $publicSuffixes)) {
            return true;
        }
    }
    
    return false;
}

// Example usage
$subdomain = 'subdomain.example.com';
if (isValidSubdomain($subdomain)) {
    echo 'Valid subdomain';
} else {
    echo 'Invalid subdomain';
}