如果用户名不存在,则写入文本文件

I'm having an issue on writing the registration form to the .txt file if a username exist. At the moment, I don't want to write out to the file if a username exist in the user.txt and print out false and if it doesn't exist, continue and write out to the user.txt file.

<?php
    if($_POST['submit'])
    {
            $usernameexist =  $_POST['usernameexist'];
            $username = $_POST['username'];
            $password = $_POST['password'];
            $firstname = $_POST['firstname'];
            $lastname = $_POST['lastname'];
            $dob = $_POST['dob'];
            $gender = $_POST['gender'];
            $email = $_POST['email'];
            $address = $_POST['address'];
            $membership = $_POST['membership'];
            $creditcard = $_POST['creditcard'];
            $cardexpiry = $_POST['cardexpiry'];
            $duration = $_POST['duration'];
            $name = "/^[A-Za-z]+$/";
            $emailaddress = "/^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,3})+$/";



            $male_status = 'unchecked';
            $female_status = 'unchecked';

            // Server side form validation using php.
            // Validate username field if empty or not.
            if (empty($username)){
                    $err_username = 'Please enter your username.';
            }else{  

                    // Load file and check if username exist
                    $filename = 'user.txt';
                    if (file_exists($filename)){
                        $fp = fopen ('user.txt', 'r'); 
                        while ($line = fgetcsv($fp,100,",")) { 
                            if ( ($line[0] == $_POST['username']) ) { 
                                $usernameexist = "Username Exist!";
                                $err_usernameexist = $usernameexist;
                            } 
                        }
                        fclose ($fp);
                    }
                    else{
                        echo '<p> File does not exist! </p>';
                    }
                    //$val_username = $username;

            }

            // Validate password field if empty or not.
            if (empty($password)){
                $err_password = 'Please enter your password.';
            }else{
                $val_password = $password;
            }

            // First Name
            if (empty($firstname)){
                $err_firstname = 'Please enter your first name.';
            }else{
                $val_firstname = $firstname;
            }

            // Last Name
            if (empty($lastname)){
                $err_lastname = 'Please enter a valid last name.';
            }else{
                $val_lastname = $lastname;
            }

            // Gender
            if (isset($_POST['submit'])){
                $selected_radio = $_POST['gender'];
                if($selected_radio == 'Male') {
                    $male_status = 'checked';
                }else if ($selected_radio == 'Female'){
                    $female_status = 'checked';
                }
            }

            // Email Address
            if (!preg_match($emailaddress, $email)){
                $err_email = 'Please enter a valid email address.';
            }else{
                $val_email = $email;
            }

            if ($_POST['membership'] != 0){
                $err_membership = 'Nothing selected!';
            }else{
                $val_membership = $membership;
                }

            // Credit Card
            if (empty($creditcard)){
                $err_creditcard = 'Field is empty, please try again.';
            }else{
                $val_creditcard = $creditcard;
            }

            // Card Expiry
            if (empty($cardexpiry)){
                $err_cardexpiry = 'Field is empty, please try again.';
            }else{
                $val_cardexpiry = $cardexpiry;
            }

            // Duration
            if (empty($duration)){
                $err_duration = 'Field is empty, please try again.';
            }else{
                $val_duration = $duration;
            }

            if (!empty($username) && !empty($password) && !empty($firstname) 
                                && !empty($lastname) && preg_match($emailaddress, $email)
                                && ($_GET['membership'] != '0') && !empty($creditcard) && !empty($cardexpiry)
                                && !empty($duration)){
                $fp = fopen ('user.txt', 'r+'); 
                while ($line = fgetcsv($fp,100,",")){
                    if($line[0] == $_POST['username']){
                        $usernameexist = "Username Exist!";
                        $err_usernameexist = $usernameexist;
                        echo 'Username EXIST AND WRONG';
                    }
                    else{
                        $output_string = $username. ", "
                        .$password. ", "
                        .$firstname. ", "
                        .$lastname .", "
                        .$dob .", "
                        .$gender .", "
                        .$email .", "
                        .$address .", "
                        .$membership .", "
                        .$creditcard .", "
                        .$cardexpiry .", "
                        .$duration ."
";

                        $fp = fopen ('user.txt', 'a');
                        fwrite ($fp, $output_string);
                        echo "<p> Your Registration was successful! </p>";
                    }
            }fclose($fp);
            }
            else{
                        echo 'Please re-check your field as field marked with "*" is required';
            }

    }

    ?>

Any help is much appreciate and please excuse my question if it seems too confusing as i am slightly new.

Thanks.

Please forgive apparent criticism but there are a lot of issues with your code and I think it will help if I point out some poor practices first:

  1. Don't keep reassigning variables. Just use them as $_POST['whatever'] there is no advantage in copying them into other memory intensive structures. It obfuscates rather than clarifying your code.
  2. DO NOT EVER store credit card details in a plain text file.
  3. Why are you using a custom CSV data structure? This is what databases are for XML at a pinch.
  4. You test for username existence twice, neither in the right place to fix the problem.

For your answer:

if (!empty($username) && !empty($password) && !empty($firstname) 
                                && !empty($lastname) && preg_match($emailaddress, $email)
                                && ($_GET['membership'] != '0') && !empty($creditcard) && !empty($cardexpiry)
                                && !empty($duration)){
                $fp = fopen ('user.txt', 'r+'); 
                while ($line = fgetcsv($fp,100,",")){
                    if($line[0] == $_POST['username']){
                        $usernameexist = "Username Exist!";
                        $err_usernameexist = $usernameexist;
                        echo 'Username EXIST AND WRONG';
                    }
                    else{
                        $output_string = $username. ", "
                        etc...

Seems to be your problem here. What this says is: "If the data is wrong, check to see if the username exists and if it does, say so, otherwise if the data is correct, post it to the file. [but don't test for username existence first]

Essentially, you are testing for the existence of the username in the wrong place.

Move the username existence check to the other side of the else. You could even (riskily) test for strlen($err_usernameexist)>0 as this will return true if the username exists.

Once again though, this is dangerous code and although it forms an interesting exercise in CSV file manipulation it is not appropriate for the apparent application type it seems to be designed for. It will also break if a user puts a comma in their data.

you could use fputcsv properly by creating an array which is immune to commas though not to quotes:

myarray=array($name,$password,$encryptedcreditcard,$etcetc);
fputcsv($fp,$myarray);

You SHOULD however save the data in mysql where you can at least AES_ENCRYPT your confidential data. Alternatively, there are plenty of AES classes posted free for PHP. Mysql will handle very large data sets quickly whilst yours just gets slower and slower with time...