0

I thought I had this figured out, but I'm running into an issue. I'm creating a URL blacklist in my application. I need to block all subdomains, directories, etc from an array of domains. Below is the array I have:

$blacklist = array(
'/\.google\./',
'/\.microsoft\./',
);   

Here is where I'm checking:

    $host = parse_url($url, PHP_URL_HOST);
    $blackList = $GLOBALS['blacklist'];
    foreach($blackList as $stop) {
        if (preg_match($host === $stop)) {
            die('blacklisted');
            }
        }

When I run this, it doesn't die as intended.

Jason
  • 13,945
  • 23
  • 82
  • 113
Paul Dessert
  • 6,193
  • 7
  • 41
  • 70
  • **There may be an appropriate time to use `$GLOBALS`, but I haven't encountered it yet**. For more see [Are global variables in PHP considered bad practice? If so, why?](http://stackoverflow.com/questions/1557787/are-global-variables-in-php-considered-bad-practice-if-so-why) – rdlowrey Jan 17 '12 at 07:35

3 Answers3

2

Your foreach loop should be like this:

foreach($blacklist as $stop) {
        if (preg_match($stop, $host)) {
            die("blacklisted\n");
        }
}

You had 2 problems:

  1. array variable was named as blacklist but you were using blackList in foreach loop.
  2. preg_match was being used incorrectly, it needs at least 2 arguments like in my answer.
anubhava
  • 664,788
  • 59
  • 469
  • 547
  • See it working here: http://ideone.com/fdmTo and print your variable `$url` using `var_dump($url);` to investigate. – anubhava Jan 17 '12 at 08:03
  • Thanks for the help! Everything you posted looks good. I did a `print_r($blackList)` and it returned an empty array. I guess that's my problem. – Paul Dessert Jan 17 '12 at 08:20
0

Without foreach:

if(preg_match('/'.implode('|', array_map('preg_quote', $blacklist)).'/i', $string))
{
   die("blacklisted");
}
tsamu
  • 21
  • 2
0

You're using preg_match wrong!

$host = parse_url($url, PHP_URL_HOST);

foreach ($blacklist as $pattern){
  $matches = array();
  preg_match($pattern, $host, $matches);
  if (count($matches)) die('blacklisted');
}
Juicy Scripter
  • 25,035
  • 5
  • 70
  • 90