Jump to content

[SOLVED] strpos() returns false for found values, it should return false for not found


adrianTNT

Recommended Posts

I have this code, the strpos in the function should return false when string is not found, correct? But instead it seems to return false for found string?

What am I soing wrong?

I can use the code like this too but it looks worong.

<?php
function check_referer($the_referer_to_check){
// list of urls to remove from referers list when reading the list of referers
$bad_referers = array('yahoo','google','.mail.live.com','search.msn','abv','google.de','google.se');
for($i=0;$i<count($bad_referers);$i++){
	// if string not found then value is FALSE, correct?
	// so why does it return values for *found values?
	if(strpos($the_referer_to_check, $bad_referers[$i]) == 'FALSE'){
		echo $bad_referers[$i].' NOT found in ' .$the_referer_to_check.'<br>'; 
		}
}
}

check_referer('google.com');
check_referer('site.com'); // this one is not in the bad_referers
check_referer('abv.bg');
?>

 

Returns:

google NOT found in google.com

abv NOT found in abv.bg

Because google in google.com returns 0, meaning the string "google" was found starting from char number 0- at the start. To avoid that, use the strict comparison:

 

if(strpos($the_referer_to_check, $bad_referers[$i]) === FALSE)

 

Notice the three '='.

 

Orio.

If it... == 'FALSE'?

 

Like, the string, FALSE?

 

Loose the quotes, and use the !== operator. The !== operator checks type and value, not just converted value.

 

<?php

function check_referer($the_referer_to_check){

$bad_referers = array('yahoo','google','.mail.live.com','search.msn','abv','google.de','google.se');

for($i=0;$i<count($bad_referers);$i++)
	if(strpos($the_referer_to_check, $bad_referers[$i]) !== FALSE)
		return TRUE;

return FALSE;
}

echo (check_referer('google.com') ? "Bad" : "Good"), "\n";
echo (check_referer('site.com') ? "Bad" : "Good"), "\n";
echo (check_referer('abv.bg') ? "Bad" : "Good"), "\n";

?>

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.