Justin, I wrote a small tutorial on adding data to text files a while ago, I'll post it below:
-----------------------------------------------------------
This tutorial is to show you how to write data to txt files. We will do this by making a simple user registration form.
Let's make a page and call it register.php and this will have the sign up form on it.
Code:
<form name="form1" method="post" action="signup.php"> Username: <input type="text" name="user"><br>Email: <input type="text" name="mail"><br>Experience: <select name="exp"> <option value="beginner">Beginner</option> <option value="intermediate">Intermediate</option> <option value="advanced">Advanced</option> </select><br> <input type="submit" name="Submit" value="Sign Up"> </form>
Now, the actual php is going to be on the signup.php page. We will write to a file called users.txt as that is what we used when retrieving the data.
To do this, we will use the fopen() function, which opens a specified file and depending on the mode you enter as the second argument, will specify how you want to write to the file.
The modes are represented by letters and here is what each mode does:
r = Opens the file for reading only and places the file pointer at the beginning of the file.
r+ = Opens the file for reading and writing and places the file pointer at the beginning of the file.
w = Opens the file for writing only and places the file pointer at the beginning of the file. If the file does not exist, it attempts to create it.
w+ = Opens the file for reading and writing and places the file pointer at the beginning of the file. If the file does not exist, it attempts to create it.
a = Opens the file for writing only and places the file pointer at the end of the file. If the file does not exist, it will try to create it (What we will use).
a+ = Opens the file for reading and writing and places the file pointer at the end of the file. If the file does not exist, it will attempt to create it.
Now, we are going to set a couple variables to start with:
Code:
$username = $_POST['user'];
$email = $_POST['mail'];
$experience = $_POST['exp']; //the data
$data = "$username | $email | $experience\n";
//open the file and choose the mode
$fh = fopen("users.txt", "a");
Next step is to actually write to the file. To do this we will use the fwrite function. This function will read the $fh variable and put the $data string into it.
Code:
fwrite($fh, $data); //close the file fclose($fh);
print "User Submitted";
Now you have done it, so just make sure your users.txt file has been CHMOD to 777 and your signup.php page should now look like this:
PHP Code:
<?php
$username = $_POST['user'];
$email = $_POST['mail'];
$experience = $_POST['exp'];
//the data
$data = "$username | $email | $experience\n";
//open the file and choose the mode
$fh = fopen("users.txt", "a");
fwrite($fh, $data);
//close the file
fclose($fh);
print "User Submitted";
?>
There it is, you now know how to store data using txt files.