Search code examples
phpstrpos

strpos() === true returns false even when there is a match


I have this:

$fi2 = "/var/www/server/poll/ips.txt"; //IP file
$mystring = $_SERVER['REMOTE_ADDR']; //IP according to server
$findme = file_get_contents($fi2);
$pos = strpos($mystring, $findme);
if ($pos === true) {
    echo "Found";
} else {    
    echo "not found"; 
}

However, it does not say "not found" even if the IP matches something in the text file. I have done

echo "$mystring $findme"; 

And it outputs my IP and the text file correctly.

I have been told that I should replace

if ($pos === true) {

with

if ($pos !== false) {

Which I did and it still does not work.

Here's the code I used to save to the text file:

//Record IP
$fi2 = "/var/www/server/poll/ips.txt"; //IP file
file_put_contents($fi2, "\r\n$mystring", FILE_APPEND); //Stick it onto the IP file

Solution

  • I just figured it out myself.

    I changed

    file_put_contents($fi2, "\r\n$mystring", FILE_APPEND); //Stick it onto the IP file
    

    To

    file_put_contents($fi2, "$mystring", FILE_APPEND); //Stick it onto the IP file
    

    I don't know why this fixed it (just starting PHP) but that's the reason it's broken, so if someone proposes an answer to fix it with the original line I'll accept it.

    Changing $pos === true to $pos !== false also was required.