使用PHP验证URL的部分内容

时间:2018-05-30 12:48:02

标签: php regex if-statement subdomain

我正在尝试使用PHP检查一个URL数组,但其中一个URL将在其前面有一些随机字符串(生成的子域)。

这是我到目前为止所做的:

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

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

唯一的问题是develop.domain.com会有一些东西摆在它面前。例如namething.develop.domain.com。 有没有办法检查网址array中的通配符,以便它可以检查127.0.0.1和匹配develop.domain.com

2 个答案:

答案 0 :(得分:1)

假设网址会像你在问题中提到的那样在子域中使用一个单词。

如果URL包含多个单词,则需要根据子域中的预期单词修改以下代码。

<?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;
}

?>

输出:

PASS domain.develop.domain.com
PASS namething.develop.domain.com

FAIL subsubdomain.domain.develop.domain.com
FAIL namething1.namething2.develop.domain.com

答案 1 :(得分:1)

最简单的方法就是像所有regex一样

// 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;
  }
}