user3219478
user3219478

Reputation:

How to read a file line by line in php and compare it with an existing string?

I tried to write this program to compare a user-name in a file with an entered user-name to check whether it exists, but the program doesn't seem to work. Please help. The program was supposed to open a file called allusernames to compare the usernames. If the user name was not found, add it to the file.

<?php
    $valid=1;
    $username = $_POST["username"];
    $listofusernames = fopen("allusernames.txt", "r") or die("Unable to open");
    while(!feof($listofusernames)) {
        $cmp = fgets($listofusernames);
        $val = strcmp($cmp , $username);

        if($val == 0) {
            echo ("Choose another user name, the user name you have entered has already been chosen!");
            $valid=0;
            fclose($listofusernames);
            break;
        } else {
            continue;
        }
    }

    if($valid != 0) {
        $finalusers = fopen("allusernames.txt", "a+");
        fwrite($finalusers, $username.PHP_EOL);
        fclose($finalusers);
?>

Upvotes: 1

Views: 3467

Answers (3)

jthawme
jthawme

Reputation: 233

I havent tested this but I wonder if you could use something like

<?php

$user = $_POST["username"];

$contents = file_get_contents("allusernames.txt");
$usernames = explode("\n",$contents);

if(in_array($user,$usernames))
{
    echo "Choose another username";
}
else
{
    $contents .= "\n".$user;
    file_put_contents("allusernames.txt",$contents);
}

I think things like file get contents etc. need a certain version of PHP but they do make things a lot nicer to work with.

This also assumes that your usernames are seperated by new lines.

Upvotes: 1

Adrian Cid Almaguer
Adrian Cid Almaguer

Reputation: 7791

Yo can do this more simple with this code:

<?php
$username = $_POST["username"];
$listofusernames = 'allusernames.txt';

$content = file($listofusernames);

if(in_array($username, $content)) {
    echo ("Choose another user name, the user name you have entered has already been chosen!");
} else {
    $content[] = $username . PHP_EOL;
    file_put_contents($listofusernames, implode('', $content));
}

?>

Upvotes: 0

Rajnikant Sharma
Rajnikant Sharma

Reputation: 606

you need to replace linefeed/newline character from each line to compare.

while(!feof($listofusernames)) {
    $cmp = fgets($listofusernames);
    $cmp = str_replace(array("\r", "\n"), '',$cmp);
    $val = strcmp($cmp , $username);
    if($val == 0) {
        echo ("Choose another user name, the user name you have entered has already been chosen!");
        $valid=0;
        fclose($listofusernames);
        break;
    } else {
        continue;
    }
}

i have added following line in you code

  $cmp = str_replace(array("\r", "\n"), '',$cmp);

Upvotes: 3

Related Questions