代码之家  ›  专栏  ›  技术社区  ›  ultraloveninja

用php验证部分url

  •  1
  • ultraloveninja  · 技术社区  · 7 年前

    我试图用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 回复  |  直到 7 年前
        1
  •  1
  •   kator    7 年前

    最简单的方法就是全力以赴 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;
      }
    } 
    
        2
  •  1
  •   d.coder    7 年前

    假设url将在子域中使用一个单词,就像您在问题中提到的那样。

    如果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