Page 1 of 1

simplify php code

Posted: Sun Sep 30, 2007 6:32 am
by benyboi
hello,

i have some code on my site to check referer and then if it is my site then the php page will work, otherwise it will display an error.

now at the moment im doing that by:

Code: Select all

$valref=substr($ref, 0, 23);

 if($valref == "http://www.xxxxxx."){
	$valref=substr($ref, 0, 27);
		if($valref == "http://www.xxxxxx.com/"){
			$ok = "yes";
		}
 }else{
	$valref=substr($ref, 0, 23);		
		if($valref == "http://xxxxxx.com/"){
			$ok = "yes";
		}
 }
but what about when i want ot add other domains? yeh i could make lots more if statements, but is there another simplere way to do it?

thanks!

Posted: Sun Sep 30, 2007 7:17 am
by VladSun

Code: Select all

$referer = $_SERVER['HTTP_REFERER'];
$pattern = '/^(http:\/\/)?([^\/]+)/i';

$referers = array('domain.com', 'www.domain.com', 'other_domain.com');

$matches = array();
preg_match($pattern, $referer, $matches);

if (in_array($matches[2], $referers))
{
	print "OK";
}

Posted: Sun Sep 30, 2007 8:01 am
by feyd
This doesn't need regex.

stripos() returning zero would work nicely in a loop.

Posted: Sun Sep 30, 2007 9:23 am
by VladSun
Yes, you are right - it's faster :)

I am wondering whether there is a PHP function like in_array, but implemented in "array_walk" manner - i.e. by using custom compare function ... Couldn't find a one in PHP documentations.

If such exists then it would be better to have a sorted array of possible referers and make a binary search on it.

Posted: Sun Sep 30, 2007 9:45 am
by feyd
look into array_filter().

Posted: Sun Sep 30, 2007 12:56 pm
by VladSun
feyd wrote:look into array_filter().
That's not exactly what I'm looking for ... it will iterate through the whole array, even worse - it will do it linearly.

EDIT: On second thought, I don't need it in this case ... One could sort the array of possible referrers, extract the referral domain from $_SERVER['HTTP_REFERER'] by using regexp and perform binary search - I think it will be much faster. :) If there are too many referrers (e.g. > 10^6) one could use hashing algorithms to perform the search...