Registration form validation problem using php and tetxt file-ThrowExceptions

Exception or error:

I created a registration form which is working fine. I save all of my users data in a txt file named users.txt which saves the the data after the button click like this:

username|password|email

here is my users.txt file:

asd|asd|asd
asd|asd|asd
sanyi|123456|asd@asd.hu
sanyi|123456|asd@asd.hu
sanyi|123456|asd@asd.hu
frici|123|vass.frigyes@gmail.com
frici|123|vass.frigyes@gmail.com
frici|123|vass.frigyes@gmail.com
frici|123|vass.frigyes@gmail.com
frici|123|vass.frigyes@gmail.com

I want to solve that the username must be unique! I tried to solve this by check the txt file before the registration and if I find the same username in the txt that the user submitted, kill the process. I can check the first line username but I have no idea how I can go to the next line, and so on…

My php code:
register.php:

<!--                   html section                             -->

<!DOCTYPE html>
<html>
<head>
    <title>Store form data in .txt file</title>
</head>
<body>

    <form action="#" method="post">
    REGISTRATION<br />
        <input type="text" name="username" placeholder = "Username"/><br />
        <input type="text" name="password" placeholder = "Password" /><br />
        <input type="text" name="password2" placeholder = "Password Again"><br />
        <input type="text" name="email" placeholder = "Email Adress"/><br />
        <input type="submit" name="submit" value = "REGISTER" />
    </form>
</body>
</html>

<!--                   php section                             -->

<?php





if(isset($_POST['submit']))
{

    //check if the username has been already taken

    $usernameToCheck = $_POST["username"];

    $userlist = file ('users.txt');
    $success = false;

    foreach ($userlist as $user) {
        $user_details = explode('|', $user);
        if ($user_details[0] == $usernameToCheck) {
            die("This user is already exsists");
        }
    }

    // the registreation itself

    $username = $_POST["username"];
    $password = $_POST["password"];
    $password2 = $_POST["password2"];
    $email = $_POST["email"];

    if(empty($username) || empty($password) || empty($password2) || empty($email)){

        die("You filled out the form wrongly! Don't let anything empty next time!");

    }else if($password !== $password2){

        die("Passwords doesnt match!");

    }else{


        $fp = fopen('users.txt', 'a');
        $line = $username."|".$password."|".$email.PHP_EOL;
        fwrite($fp, $line);

        fclose($fp);

    }


}



?>
How to solve:

Leave a Reply

Your email address will not be published. Required fields are marked *