Duplicate user creation in script

I’ve created a very simple form to create a new user, however, the check of the userfile doesn’t appear to be working and the script will happily create a duplicate.

Not sure why.

<?php
if ($_SERVER["REQUEST_METHOD"] === "POST") {
    $username = $_POST["username"];
    $password = $_POST["password"];
    $town = $_POST["town"];
    $country = $_POST["country"];
    $date = date("d-m-Y"); // Get the current date

    // Check if the username already exists in the text file
    $users = file("users.txt", FILE_IGNORE_NEW_LINES);
    if (in_array($username, $users)) {
        // Username already exists, display an error message or redirect
        header("Location: newusererror.html");
        exit;
    }

    // Create a new line with the username, password, town, and country
    $line = $username . "," . $password . "," . $town . "," . $country . "," . $date . "\n";

    // Append the line to the text file
    file_put_contents("users.txt", $line, FILE_APPEND);

    // Redirect to a success page or perform other actions
    header("Location: newusersuccess.html");
    exit;
}
?>

If the lines you are storing in the file consist of -

How would - in_array($username, $users) possibly find a match? Wouldn’t you need to test just the username part of each line?

$users holds the filename (users.txt)

I hope this is just for learning. You should never use a text file to store user credentials.

Testing purposes only

Sponsor our Newsletter | Privacy Policy | Terms of Service