matteo
matteo

Reputation: 147

Check the hostname with preg_match

I have a problem using preg_match. (I'm very new to regular expressions)

if(preg_match('^/http:\/\/myWebsite\.com\/', $_SERVER['HTTP_REFERER'])) {
return true;
}
else{
return false;
}

Always returns false and it shouldn't. Where am I wrong?

UPDATE

Hi everybody ! Thanks all of you for your help ! Every check is fine now

Upvotes: 1

Views: 1597

Answers (4)

Álvaro González
Álvaro González

Reputation: 146330

Your regular expression is missing the delimiters, as PHP should have warned you:

$_SERVER['HTTP_REFERER'] = 'http://myWebsite.com/foo.html';
var_dump( preg_match('^/http:\/\/myWebsite\.com\/', $_SERVER['HTTP_REFERER']) );

... triggers:

Warning: preg_match(): No ending delimiter

Since you are allowed to choose your own delimiter, it's simpler to pick one that's not in the text:

preg_match('@^http://myWebsite\.com/@', $_SERVER['HTTP_REFERER'])

Additionally, if the text is not fixed (not this case I presume), PHP can escape it for you:

preg_match('/^' . preg_quote('http://myWebsite.com/', '/') . '/', $_SERVER['HTTP_REFERER'])

I suggest you configure your development box to display all possible errors. You have several ways to do so:

  1. Edit your php.inifile:

    error_reporting = E_ALL | E_STRICT
    display_errors = On
    
  2. Put this on top of your script:

    <?php
    
    error_reporting(E_ALL | E_STRICT);
    ini_set('display_errors', TRUE);
    
  3. If PHP runs as Apache module, you can also use an .htaccess file:

    # Print E_ALL | E_STRICT from a PHP script to get the appropriate number:
    php_value error_reporting 2147483647
    php_flag display_errors on
    

Upvotes: 2

webbiedave
webbiedave

Reputation: 48897

return (boolean) preg_match('#^http://myWebsite\.com/#i', $_SERVER['HTTP_REFERER']);

You can choose your own delimiter to make things easier. Here I've chosen #.

I also added an i modifier at the end to make the search case-insensitive.

I removed the if/else branches and just returned the result of preg_match (type-casted to boolean).

Upvotes: 1

Aram Kocharyan
Aram Kocharyan

Reputation: 20421

preg_match requires a valid delimiter. It may be throwing a warning that you aren't seeing. You should place the carat ^ after the opening /.

Also try error_reporting(E_ALL); to see any warnings etc.

Upvotes: 0

Philippe Plantier
Philippe Plantier

Reputation: 8073

It should be '/^http:\/\/myWebsite\.com\//i' (note the caret (^) position, and the i for case-insensitive matching)

Upvotes: 0

Related Questions