Creating a News System with PHP - Part 1 - Storing the Form Data
(Page 3 of 4 )
At this point, we have checked the form to make sure the data looks like we want it. Now, it's time to put the data into our text file. In order for this to work, you will need to make sure that the webserver process has write access to the directory you plan to store the file in. If the webserver is unable to write to the directory, you will not be able to store any information.
The first thing we need to do in order to write to a file is open it up. To do this, we will use the fopen function.
<?php $fp = fopen('news.txt','a'); if(!$fp) { echo "Error opening file!"; exit; } ?> |
Ok, what we did there is open up a file called news.txt that is in the same directory as the script we are running. The 'a' specifies that we want to append information to the end of this file. If the file doesn't exist, it will attempt to create it. I also added a bit of error checking. If the script is unable to open to file for whatever reason, it will spit out an error and halt.
Next, let's build the line we want to put into this file. We want to store the date and the information inputted on the form. Remember that we also want to keep everything on one line, so we are going to turn any newlines into a BR tag with the str_replace function. Then we need to go back and add a newline to the end of the data so that the next item we put in starts on the next line of the file.
<?php $line = date("m.d.y") . "|" . $HTTP_POST_VARS['name']; $line .= "|" . $HTTP_POST_VARS['news']; $line = str_replace("\r\n","<BR>",$line); $line .= "\r\n"; ?> |
Good, now that should do it for getting our news into a text file. Let's put it all together and see how it looks.
<? //this should all go into one file. I would name it addnews.php if($HTTP_POST_VARS['submit']) { if($HTTP_POST_VARS['password'] == 'pass') { if(!$HTTP_POST_VARS['name']) { echo "You must enter a name"; exit; } if(!$HTTP_POST_VARS['news']) { echo "You must enter some news"; exit; } if(strstr($HTTP_POST_VARS['name'],"|")) { echo "Name cannot contain the pipe symbol - |"; exit; } if(strstr($HTTP_POST_VARS['news'],"|")) { echo "News cannot contain the pipe symbol - |"; exit; } $fp = fopen('news.txt','a'); if(!$fp) { echo "Error opening file!"; exit; } $line = date("m.d.y") . "|" . $HTTP_POST_VARS['name']; $line .= "|" . $HTTP_POST_VARS['news']; $line = str_replace("\r\n","<BR>",$line); $line .= "\r\n"; fwrite($fp, $line); if(!fclose($fp)) { echo "Error closing file!"; exit; } } else { echo "Bad Password"; } }
?> <FORM ACTION="<?=$PHP_SELF?>" METHOD="POST" NAME="newsentry"> Your name:<BR> <INPUT TYPE="text" SIZE="30" NAME="name"><BR> The News:<BR> <TEXTAREA NAME="news" COLS="40" ROWS="5"></TEXTAREA><BR><BR> News Password:<BR> <INPUT TYPE="password" SIZE="30" NAME="password"><BR> <INPUT TYPE="submit" NAME="submit" VALUE="Post it!"><BR> </FORM> |
Next: Displaying the News >>
More Miscellaneous Articles
More By Matt Wade