Home arrow PHP arrow Creating a News System with PHP
PHP

Creating a News System with PHP


For those web developers that are wishing to create a news service on a website, Matt has come to your aide in this article. It entails two lessons that will guide you towards this goal.

Author Info:
By: Matt Wade
Rating: 4 stars4 stars4 stars4 stars4 stars / 20
April 14, 2003
TABLE OF CONTENTS:
  1. · Creating a News System with PHP
  2. · Lesson 2
  3. · The Final Product

print this article
SEARCH DEVARTICLES

Creating a News System with PHP
(Page 1 of 3 )

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 lesson of "Creating a News System".

This first lesson 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!


blog comments powered by Disqus
PHP ARTICLES

- Removing Singletons in PHP
- Singletons in PHP
- Implement Facebook Javascript SDK with PHP
- Making Usage Statistics in PHP
- Installing PHP under Windows: Further Config...
- File Version Management in PHP
- Statistical View of Data in a Clustered Bar ...
- Creating a Multi-File Upload Script in PHP
- Executing Microsoft SQL Server Stored Proced...
- Code 10x More Efficiently Using Data Access ...
- A Few Tips for Speeding Up PHP Code
- The Modular Web Page
- Quick E-Commerce with PHP and PayPal
- Regression Testing With JMeter
- Building an Iterator with PHP

Watch our Tech Videos 
Dev Articles Forums 
 RSS  Articles
 RSS  Forums
 RSS  All Feeds
Write For Us 
Weekly Newsletter
 
Developer Updates  
Free Website Content 
Contact Us 
Site Map 
Privacy Policy 
Support 

Developer Shed Affiliates

 




© 2003-2017 by Developer Shed. All rights reserved. DS Cluster - Follow our Sitemap
Popular Web Development Topics
All Web Development Tutorials