You have some logic issues.
$usernames is never empty. So you can replace this
if (empty($usernames)) {
$usernames[] = $username1;
} else {
if (in_array($username1, $usernames)) {
echo "Duplicate username: " . $username1;
} else {
$usernames[] = $username1;
}
}
by this
if (in_array($username1, $usernames)) {
echo "Duplicate username: " . $username1;
} else {
$usernames[] = $username1;
}
and more, $username1 is the posted username, there are no reason to put it in the $usernames collection.
Then you can replace this
if (in_array($username1, $usernames)) {
echo "Duplicate username: " . $username1;
} else {
$usernames[] = $username1;
}
by this
if (in_array($username1, $usernames)) {
echo "Duplicate username: " . $username1;
}
And more, you do not need collect the usernames. You only need to check the current value in the loop. If the value match with $username1, the username exists. Using a break we can terminate the loop and prevent memory leaks.
See the the code
if (isset($_POST[ 'button1' ])) {
$username1 = $_POST[ 'username' ];
$users = fopen("users.txt", "r"); //open file
while ( ! feof($users)) {
$line = fgets($users, 4096); //read one line
list ($firstname, $lastname, $username) = explode(" ", $line);
if (strtolower($username) == strtolower($username1)) {
echo "Duplicate username: ".$username1;
break;
}
}
fclose($users); #close file
}
Additionally i have some suggestions:
- use the comma (,) character and save the file as a csv (comma separated values) file. With comma, you prevent errors with names that contains spaces.
- try to write modular code. In this case, you can create a function called usernameExists that returns true if the username exists and false it not.
- to compare usernames apply the trim and strtolower over the values
Here the final code
<?php
function usernameExists($username1)
{
$exists = false;
if (file_exists('users.csv')) {
$users = fopen("users.txt", "r");
$username1 = trim($username1);
$username1 = strtolower($username1);
while ( ! feof($users)) {
$line = fgets($users, 4096);
list ($firstname, $lastname, $username) = explode(",", $line);
$username = trim($username);
$username = strtolower($username);
if ($username == $username1) {
$exists = true;
break;
}
}
fclose($users);
}
return $exists;
}
// the logic is very simply now
if (isset($_POST[ 'button1' ])) {
$username1 = $_POST[ 'username' ];
if (usernameExists($username1)) {
echo "Duplicate username: ".$username1;
}
}
?>