Reputation: 147
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
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:
Edit your php.ini
file:
error_reporting = E_ALL | E_STRICT
display_errors = On
Put this on top of your script:
<?php
error_reporting(E_ALL | E_STRICT);
ini_set('display_errors', TRUE);
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
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
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
Reputation: 8073
It should be '/^http:\/\/myWebsite\.com\//i'
(note the caret (^) position, and the i for case-insensitive matching)
Upvotes: 0