Search code examples
phpregexif-statementsubdomain

Validate parts of URLs with PHP


I'm trying to check against an array of URL's with PHP, but one of the URL's will have some random strings in front of it (generated sub domain).

This is what I have so far:

<?php
$urls = array(
    '127.0.0.1',
    'develop.domain.com'
);
?>

<?php if (in_array($_SERVER['SERVER_NAME'], $urls)) : ?>
//do the thing
<?php endif; ?>

The only thing is that the develop.domain.com will have something in front of it. For example namething.develop.domain.com. Is there a way to check for a wildcard in the array of URL's so that it can check for the 127.0.0.1 and and matches for develop.domain.com?


Solution

  • Simplest way is to go all regex like this

    // Array of allowed url patterns
    $urls = array(
      '/^127.0.0.1$/',
      '/^(([a-z0-9]|[a-z0-9][a-z0-9\-]*[a-z0-9])\.)*(develop.domain.com)$/i'
    );
    // For each of the url patterns in $urls,
    // try to match the $_SERVER['SERVER_NAME']
    // against
    foreach ($urls as $url) {
      if (preg_match($url, $_SERVER['SERVER_NAME'])) {
        // Match found. Do something
        // Break from loop since $_SERVER['SERVER_NAME']
        // a pattern
        break;
      }
    }