Skip to content

Instantly share code, notes, and snippets.

@nhalstead
Last active January 16, 2019 16:15
Show Gist options
  • Save nhalstead/612263f7d6deecf771d5756a4019535d to your computer and use it in GitHub Desktop.
Save nhalstead/612263f7d6deecf771d5756a4019535d to your computer and use it in GitHub Desktop.
This is to allows you to test domains to see if they match a url based rule list. This has "regex" matching in it to detect any subdomain `*.example.com` and block others using `!ebay.com`.
<?php
$authDomains = [
"google.com", // Allow
"*.google.com", // Allow [Any].google.com
"!webconsole.google.com", // Block
"club.hosting.com", // Allow
"webcome.go.google.com" // Allow
];
$websiteURL = "webconsole.google.com";
echo $websiteURL."<br />";
print( allowedDomain($authDomains, $websiteURL)?"200":"403" );
/**
* Allowed Domains
*
* @param Array Domain List/Rules
* @param String Domain in Question to match, This can be a Domain or a URL.
* @param Boolean Have all of the domains blocked unless specified by the rules.
* @return Boolean Is the Domain allowed based on the Conditions of the List
*/
function allowedDomain($domainList = array(), $domain, $blacklistAll = false){
// Get the Domain
$parseUrl = parse_url(trim($domain));
if(isset($parseUrl['host'])) {
$host = $parseUrl['host'];
}
else {
$path = explode('/', $parseUrl['path']);
$host = $path[0];
}
$h = trim($host);
// Processing of the URL and the Domain List
$allowed = $blacklistAll;
foreach($domainList as $i => $d){
//echo $allowed?"Yes|<br />":"No|<br />";
//echo $d."<br />";
// Check to see if this rule is an any. *.example.com
if($d[0] == "*"){
removePrefix($d, "*"); // Remove *
removePrefix($d, "."); // Remove .
if(endswith($h, $d) == $d){
$allowed = true;
}
}
// Check to see if this is a blocking rule for a a specfic domain,
// Keep in mind that this is really only good when an entire domain
// uses a *. and you want to block one domain of it.
else if($d[0] == "!"){
removePrefix($d, "!"); // Remove !
if($h == $d){
$allowed = false;
}
}
// Basic Rule of matching an exact domain.
else {
if($d == $h){
$allowed = true;
}
}
}
return $allowed;
}
function removePrefix(&$str, $prefix = ""){
if (substr($str, 0, strlen($prefix)) == $prefix) {
$str = substr($str, strlen($prefix));
}
}
/**
* @link https://stackoverflow.com/a/619725/5779200
*/
function endswith($string, $test) {
$strlen = strlen($string);
$testlen = strlen($test);
if ($testlen > $strlen) return false;
return substr_compare($string, $test, $strlen - $testlen, $testlen) === 0;
}
?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment