试图通过php explode删除子域

时间:2013-07-24 19:38:59

标签: php validation

尝试为安全数据库编写验证php代码,所以我已经编码到这里

问题是此代码验证了与子域

的链接

喜欢如果

unsafeurl = http://remove.facebook.com/anything //it works (Shows Valid) 

但如果

,这不起作用
unsafeurl = http://facebook.com/anything //not works (Shows invalid because of $da in place of $do ... i have explode (.) here)

所以,我被困在最后一行做了..请帮助我

<?php

      $url=$_POST['unsafeurl']; 

      $safeurl = "facebook";


      $front = explode("/", $url); 
      $host = $front[2]; 

      $domain = explode(".com", $front[2]); 
      $do = $domain[0];

      $domain = explode(".", $url); 
      $da = $domain[1];

      echo $da; 
      echo "<br />"; 

     if($da==$safeurl) {

       echo "valid";

    }
    else
    { 
        echo "invalid";        
    }

    ?>

2 个答案:

答案 0 :(得分:2)

我会改变一些事情:

  $safeurl = "facebook.com";

  # Use parse_url to get host from URL
  $explode = explode(".", parse_url($url, PHP_URL_HOST));

  # Get last two elements of . explode
  $count = count($explode);
  $count = $count - 2;
  $da = $explode[$count];
  $count++;
  $da .= ".".$explode[$count];

这应该返回$da作为facebook.com for anything.here.facebook.com

如果你想让它更高级,那么它可以处理多个URL和.co.uk等:

  $safeurl[] = "facebook.com";
  $safeurl[] = "google.co.uk";

  # Use parse_url to get host from URL
  $explode = explode(".", parse_url($url, PHP_URL_HOST));


  $valid = 0;
  foreach($safeurl as $checkurl) { 
    # Get number of elements in safeurl
    $safecount = count(explode(".", $checkurl));

    # Get last $safecount elements of . explode
    $count = count($explode);
    $count = $count - $safecount;
    $da = $explode[$count];
    $count++;
    while ($explode[$count]) {
     $da .= ".".$explode[$count];
     $count++;
    }
    if($da==$checkurl) {
      $valid = 1;
    }
  }
  if ($valid==1) { echo "Valid"; }

有人可以验证,但我相信这一切都是正确的。我很快就做到了。

答案 1 :(得分:1)

您可能想要调查PHP parse_url()函数

虽然我不清楚你认为什么是“安全”的URL(它是否必须有.com TLD?它必须是facebook域吗?),这很容易将主机部分隔离开来您要检查的网址。如果网址格式不正确,它也会返回false

所以你可以这样做:

$url = $_POST['unsafeurl'];
$host = parse_url($url, PHP_URL_HOST);
if (false === $host) {
    // bad URL
} else {
    // get domain with TLD removed
    $domain_minus_tld = substr($host, 0, strpos($host, '.', -1));
}

如果您专门尝试验证这是一个Facebook网址,您可能会执行类似

的操作
$url_is_facebook = false;
$url = $_POST['unsafeurl'];
$host = parse_url($url, PHP_URL_HOST);
if (false === $host) {
    // bad URL
} else {
    // see if this is facebook
    $pattern = '/^(www\.)?facebook\.com$/';
    if (preg_match($pattern, $host)) {
        $url_is_facebook = true;
    }
}