Writing To A File Using Fopen
Their will be many different instances when you might need to write to a file. What we are going to do now is create an HTML form, and a PHP code so when you click submit on the HTML form it writes the users input to a file.
In this PHP script, we are going to be using the /n function, fopen, fput, and fclose commands.
First, we are going create an HTML page that has the following code.
1 2 3 4 5 6 7 | //Mypage.php //create the form <form method=post action="writetofile.php"> Enter Name: <input type="text" name="name"> <input type="submit" value="Subscribe"> </form> //End Mypage.php |
OK, now that we have created the HTML form for the user to enter their input we need the information to be written to a file. Create another page called writetofile.php
1 2 3 4 5 6 7 8 9 | //writetofile.php //at the top of the PHP page enter the following code <?php $a = fopen("/home/pinehead/public_html/sighnup.txt", "a"); //Now that we have clarified the file location we are going to write the information to it. fputs($a, "$name\n"); //-> \n ends the line with a carrige return fputs($a, "\n"); //-> Creates a blank line for the next name. fclose($a); ?> //-> End Writetofile.php |
There ya have it. Your very own script that can write to a file! Go program! Good Luck!