WeberDev.com PHP and MySQL Code

LOG IN
BEGINNER GUIDES  |  PHP CLASSES  |  CODE SEARCH  |  ARTICLES SEARCH  |  PHP FORUMS  |  PHP MANUAL  |  PHP FUNCTIONS LIST  |  WEB SITE TEMPLATES
Start typing to search for PHP and MySQL Code Snippets and Articles Search
Submit a code Example / Snippet Submit Your Code
Search Engine Optimization Monitor SEO Monitor
Web Site UpTime Monitor UpTime Monitor
WeberDev's Monthly code contest PHP Code Contest
Your Personal Examples List My Favorite Examples
Your Personal Articles List My Favorite Articles
Edit Account Info Update Your Profile
PHP Code Search
Web Development Forums
Learn MySQL Playing Trivia
PHPBB2 Templates
Web Development Index
PHP Web Logs (BLogs)
Web Development Resources
Web Development Content
PHPClasses
PHP Editor
PHP Jobs
Vision.To Design
Ajax Tutorials
PHP Programming Help
PHP/MySQL Programming
Webmaster Resources
Webmaster Forum
XML meta language
website builder
Submit Site
Forex Trading Online forex trading platform

Go Back Add a Comment Send this Article to a friend Add this Article to your personal favoritest for easy future access to your favorite Code Examples and Articles. Submit a code example Print this code example.
BACK ADD A COMMENT SEND TO A FRIEND ADD TO MY FAVORITES SUBMIT AN ARTICLE PRINT
Title : Creating a News System with PHP - Part 1
Categories : PHP, Content Management
codewalkers
codewalkers
Date : 2002-12-21
Grade : 0 of 5 (graded 0 times)
Viewed : 4223
Search : More Articles by codewalkers
Action : Grade This Article
Tools : My Favotite Articles


  Submit your own code examples 
 


Getting Started

So, you want to display news on your site? Think it'd be pretty cool to have a page where you can enter something each day and then the whole world gets to see it? Well, I'm here to tell you how in this first installment of "Creating a News System".

First installment? That's right. This first tutorial is going to cover just the very basics - a news system that reads and writes to a text file and that's about it. In the second installment, we will move over to a database. And then in the third installment, we will incorporate features such as commenting and user authentication.

Ok, let's get started. So, what do we need to do first? Well, obviously we can't display any news unless we have news to display. So, let's first build our interface to accept new news. For this, we will use a simple HTML form. We need inputs for a name and the news. We also need an input for a password. In this first installment, we are only going to secure our page with a simple password. In the third part of this tutorial we will add multiple users authenticated from a database. Ok, so the code for our input form should look something like this:


<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>


Validating the Form

Ok, so we have a form where we can enter in our news. Now, we need to take the news and put it into our text file. Before we do that though, we need to check the password that was entered and check if it is correct. Now, when I deal with forms, I always access the form variables via the $HTTP_POST_VARS array. Some people don't do this, but you will see throughout all my examples that I do. First, let's check if the form has been submitted:


<?PHP
if($HTTP_POST_VARS['submit']) {
echo
"The form has been submitted";
}
?>




Ok, obviously that doesn't actually do anything with the submitted form, but it does check to see if it was submitted. Now, we can add some other code to actually process the form. First thing we need to do is check that password and see if it is correct.


<?PHP
if($HTTP_POST_VARS['submit']) {
if(
$HTTP_POST_VARS['password'] == 'mysecretpassword') {
echo
"The form has been submitted";
} else {
echo
"Bad Password";
}
}
?>


Now, this isn't the most secure way to do things. But, for simplicity that is the way we are going to do it for now. The next step is to validate that we actually have data in the other two fields. Another couple of if statements should take care of that bit.


<?PHP
if($HTTP_POST_VARS['submit']) {
if(
$HTTP_POST_VARS['password'] == 'mysecretpassword') {
if(!
$HTTP_POST_VARS['name']) {
echo
"You must enter a name";
exit;
}
if(!
$HTTP_POST_VARS['news']) {
echo
"You must enter some news";
exit;
}
echo
"The form has been submitted";
} else {
echo
"Bad Password";
}
}
?>


Ok, one last thing we need to do to validate the form. When we store the data in the file, we are going to store each entry on one line. I plan to separate each piece of information with a pipe symbol ( | ). We need to make sure that none of the data already contains a pipe symbol, or our whole storage system will fail. In order to do that, we will use the strstr function. This function will return false if what we are looking for is not found in the string. If it returns anything, it will evaluate as true and we will know that a pipe symbol exists in the data we are checking.


<?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;
}
} else {
echo
"Bad Password";
}
?>


Storing the Form Data

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>


Displaying the News
So, we have a way to get the data from our browser into a text file. Now all we need to do is display the news. This is the simple part. Basically, all we are going to do is read the file into an array. Then, because the newest information is at the end of the array, we need to reverse the order of the data in the array. Then just seperate our data into its different parts. Last, we display it. So, let's do it.

First step, let's get the data into an array. For that we will use the file function. This function reads a file into an array. Each line in the file becomes an element in the array. Exactly what we need.


<?PHP
$data
= file('news.txt');
?>


Next, we want to reverse the array so that we are reading the newest news first. For that we will use the array_reverse function. Simple eh?





<?PHP
$data
= file('news.txt');
$data = array_reverse($data);
?>


Ok, so we have the data back out of the text file. What we need to do now is split each line back up into a date, a name and the news. The explode function will do exactly what we want. So, we will run a loop for as many elements as there are in our array and split each element with the explode function. While we are at it, we will echo out our results. I am also using the trim function on each element to remove the newline at the end.


<?PHP
$data
= file('news.txt');
$data = array_reverse($data);
foreach(
$data as $element) {
$element = trim($element);
$pieces = explode("|", $element);
echo
$pieces[2] . "<BR>" . "<b>Posted by " . $pieces[1] . " on " . $pieces[0] . "</b><BR><BR>";
}
?>


Place that into your page wherever you want the news to display, and bam you've got news.

Thanks for tuning in for this first lesson on creating a news system in PHP. In the next lesson we will start saving all our data in a database. Till then, keep coding!









PHP 101 Part 15 of 15 : No News Is Good News
Categories : PHP, Beginner Guides, Content Management
Implementing a Template Based Web Site With PHP
Categories : PHP, Content Management
Build Your Own KlipFolio Klip With PHP
Categories : XML, Content Management, PHP
Working with Dates and Times in PHP
Categories : PHP, Date Time
10 PHP Functions I Bet You Didn't Know About!
Categories : PHP, PHP Functions, Filesystem, Arrays, Errors and Logging
Date Arithmetic With MySQL
Categories : PHP, Databases, MySQL, Date Time
Using the .NET Assembly in PHP
Categories : PHP, .NET
Saving Images in MySQL
Categories : MySQL, PHP, Graphics, Databases
PHP References Explained
Categories : PHP References, PHP
Aspect-Oriented Programming and PHP
Categories : PHP, Aspect Oriented Programming
Beginners guide to PHP and MySQL
Categories : PHP, Beginner Guides, Databases, MySQL, Installation
Logging with PHP
Categories : PHP, Log Files
Who's Linking?
Categories : PHP, Beginner Guides, To PHP
Building A Persistent Shopping Cart With PHP and MySQL
Categories : PHP, MySQL, Databases, Ecommerce
Generating One-Time URLs with PHP
Categories : PHP, URLs