Reputation: 2139
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
?
Upvotes: 1
Views: 90
Reputation: 959
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;
}
}
Upvotes: 1
Reputation: 2038
Assuming that URL will use one word in sub-domain like you mentioned in your question.
If URL consists of more than one word then the following code needs to be modified as per expected word in sub-domain.
<?php
// Supported URLs array
$urls = array(
'127.0.0.1',
'develop.domain.com'
);
// Server name
//$_server_name = $_SERVER['SERVER_NAME'];
$_server_name = 'namething.develop.domain.com';
// Check if current server name contains more than 2 "." which means it has sub-subdomain
if(substr_count($_server_name, '.') > 2) {
// Fetch sub-string from current server name starting after first "." position till end and update it to current server name variable
$_server_name = substr($_server_name, strpos($_server_name, '.')+1, strlen($_server_name));
}
// Check if updated/filterd server name exists in our allowed URLs array
if (in_array($_server_name, $urls)){
// do something
echo $_server_name;
}
?>
Output:
PASS domain.develop.domain.com
PASS namething.develop.domain.com
FAIL subsubdomain.domain.develop.domain.com
FAIL namething1.namething2.develop.domain.com
Upvotes: 1