Jump to content

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


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";

?>

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • 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.