2

I have a file which is basically a list of names in that format:

name.lastname
name.lastname
name.lastname
myname.mylastname
name.lastname

and I want to check whether a string I have is equal to one of the names (with the dot).

Thats what I tried already:


$username = "myname.mylastname"; 
$boolean = False; 
$handle = fopen("thelist.txt","r");
while (($line = fgets($handle)) !== false) {
        if ($line === $username){
            $liste = True; 
        }
    }

after that list keeps being False and I dont know why.

Thanks in advance :)

1 Answers1

2

There are a few potential issues I see.

First $boolean = False; while $liste = True;, so you may have a potential typo in your output variable.

Second issue is that thelist.txt is not an absolute path. So the file resource may have failed to be loaded. It is highly recommended that you use an absolute path to file resources such as /full/path/to/file or __DIR__ . '/path/to/file'.

The main issue is that fgets will include the \r and \n at the end of each line in the file, that does not exist in the compared string variable. You can use trim to remove extraneous line endings and white spaces to compare with the string variable.

Example: https://3v4l.org/4VG4D

$username = "myname.mylastname"; 
$liste = false; 

$handle = fopen("thelist.txt", 'rb');
while (false !== ($line = fgets($handle))) {
    if (trim($line) === $username){
        $liste = true;
        break; //stop at first match
    }
}
fclose($handle);
var_dump($liste); //true
Will B.
  • 17,883
  • 4
  • 67
  • 69