Navigation Menu

Skip to content

Instantly share code, notes, and snippets.

@mjangda
Created January 17, 2012 00:27
Show Gist options
  • Star 7 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save mjangda/1623788 to your computer and use it in GitHub Desktop.
Save mjangda/1623788 to your computer and use it in GitHub Desktop.
Checks if a given url matches a domain whitelist
<?php
function my_is_valid_domain( $url ) {
$whitelisted_domains = array( 'mydomain.com', 'mydomain.net' );
$domain = parse_url( $url, PHP_URL_HOST );
// Check if we match the domain exactly
if ( in_array( $domain, $whitelisted_domains ) )
return true;
$valid = false;
foreach( $whitelisted_domains as $whitelisted_domain ) {
$whitelisted_domain = '.' . $whitelisted_domain; // Prevent things like 'evilsitetime.com'
if( strpos( $domain, $whitelisted_domain ) === ( strlen( $domain ) - strlen( $whitelisted_domain ) ) ) {
$valid = true;
break;
}
}
return $valid;
}
<?php
$domains = array( 'http://mydomain.com', 'http://www.mydomain.com', 'http://mydomain.com.evilsite.com', 'http://mydomain.com.mydomain.net', 'http://evilsitemydomain.com' );
foreach( $domains as $domain ) {
echo $domain . "\n";
var_dump( is_valid_time_domain( $domain ) );
}
@hearvox
Copy link

hearvox commented May 14, 2016

Thanks, just what I need. A couple comments:

  1. function in the test should be my_is_valid_domain (you have is_valid_time_domain).
  2. I added a strtolower so, e.g., the valid URL http://MyDomain.com would pass.

So test.php line 6 is:
var_dump( my_is_valid_domain( strtolower( $domain ) ) );

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment