Home arrow PHP arrow Page 2 - 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 - Lesson 2
(Page 2 of 3 )

Review of Lesson 1

Well, I know in the first installment I said we would be adding database capabilities in this second installment. Sorry to disappoint, but I felt there were other things we needed to touch on before going to databases. Namely, the ability to delete and edit news that we have already added. If you haven't read the first tutorial in this series, I highly recommend you go check it out then come back to this one. I will be building on the foundations that we created in the first lesson.

Remember back to the first lesson, we ended up with two scripts. One that actually displayed our news and one that we used to enter the news. What I plan to do in this tutorial is to only modify the administrative script. But, in order to delete or edit news, we need to see that news. So, I am going to add the news displaying script to the admin script. And then we will go from there. The two added together should look something like the following.

<?
echo "<H1><u>Current News</u></H1>\n";
$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>";
}
echo "<HR>\n";
echo "<H1><u>Add News</u></H1>\n";
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;
        }
        echo "<b>News added!</b>\n";   
    } 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>

Great, now that we have our "new" admin script. Let's get to doing something new with it.

Adding Options to the Display

The first thing we need to do is add links next to each news item so that we have a way to tell the script we want to edit or delete the item. So, let's get to adding those links.

For the administrative script, I really don't care if the newest news is first. In fact, I would rather have the oldest news first. It just makes things easier. So, remember where we used the array_reverse function? Well, I'm just going to take it out for this administrative script.

Now that we have the news in the order of oldest to newest, let's add some links for delete and edit next to the "Posted by" line of each item. We are going to need to have a way to address each news item. We already have the information in an array, and there is a key associated with that array. So, why don't we just use that? In order to use the key, we need it defined somehow. The following change will allow us to use the key.

<?PHP
foreach($data as $element) {

should be changed to:

foreach($data as $key=>$element) {
?>
 

Now that we have the key, we can add a unique URL for each news item to delete or edit it. Simply make the following change.

<?PHP
echo $pieces[2] . "<BR>" . "<b>Posted by " . $pieces[1] . " on " . $pieces[0] . "</b><BR><BR>";

should be changed to:

echo $pieces[2] . "<BR>" . "<b>Posted by " . $pieces[1] . " on " . $pieces[0] . "</b>\n";
echo " <a href=\"$PHP_SELF?action=delete&id=$key\">Delete</a>\n";
echo " <a href=\"$PHP_SELF?action=edit&id=$key\">Edit</a>\n";
echo "<BR><BR>\n";
?>
 

This is going to give us two links after each "Posted by" line that will allow us to delete and edit news.

Deleting an Item

Ok, let's make the links actually do something! Let's deal with the delete link first. It is a bit less complicated than the edit link. First thing we will need to do is add a line of code that checks to see if the delete link has been clicked. We will check to see if the $action variable is set to delete with some code like this.

<?PHP
if($action == "delete") {
?>
 

Simple enough eh? Ok, now we need to check a password to make sure it is ok to delete it and at the same time we will be confirming the deletion. We are basically going to do the same thing as we would to display all the news, except we are going to use the id we passed to the delete portion of the script to only display the one news item we want to delete.

<?PHP
if($action == "delete") {
    echo "<H2>You are about to delete the following news item.</H2>\n";
    $data = file('news.txt');
    $element = trim($data[$id]);
    $pieces = explode("|", $element);
    echo $pieces[2] . "<BR>" . "<b>Posted by " . $pieces[1] . " on " . $pieces[0] . "</b>\n";
    echo "<BR><BR>\n";
    echo "Are you sure you want to delete this news item? If so, enter the password and click on Delete.<BR>\n";
    echo "<FORM ACTION=\"$PHP_SELF?action=delete\" METHOD=\"POST\" NAME=\"deleteform\">\n";
    echo "Password:<BR>\n";
    echo "<INPUT TYPE=\"password\" SIZE=\"30\" NAME=\"password\"><BR>\n";
    echo "<INPUT TYPE=\"hidden\" NAME=\"id\" VALUE=\"$id\">\n";
    echo "<INPUT TYPE=\"submit\" NAME=\"submit\" VALUE=\"Delete\"><BR>\n";
    echo "</FORM>\n";
    exit;
}
?>

You'll notice that I included a hidden field that holds the id that was passed to the delete portion of the script. The reason I did this is that we will still need this id when we actually delete the news item. Now, what we need to do is add some code that checks to see if the action is set to delete AND the password field of the form has been set.

<?PHP
if($action == "delete" && isset($HTTP_POST_VARS['password'])) {
?>

Ok, that should suffice. That line should go to the very top of our script. Definitely make it above the last snippet that checked for an action of delete. If we don't check this first, things won't execute in the order we want them to. Now, let's check the password and then actually delete the news item.

<?PHP
if($action == "delete" && isset($HTTP_POST_VARS['password'])) {
    //obviously you should change this password on the next line
    if($HTTP_POST_VARS['password'] == "deletepass") {
        $data = file('news.txt');
        //this next line will remove the single news item from the array
        array_splice($data,$id,1);
        //now we open the file with mode 'w' which truncates the file
        $fp = fopen('news.txt','w');
        foreach($data as $element) {
            fwrite($fp, $element);
        }
        fclose($fp);   
        echo "Item deleted!<BR><BR>\n";   
        echo "<a href=\"$PHP_SELF\">Go Back</a>\n";
        exit;
    } else {
        echo "Bad password!\n";
        exit;
    }
}
?>

Editing an Item

Great, we now are able to delete items that we previously added to the news. So, now we need to be able to edit them also. Let's start off the same way that we did with the delete. We will add a line of code to check for the action of edit.

<?PHP
if($action == "edit") {
?>

We will just grab the information out of the file like we did with the delete, except this time we will put it in a HTML form so that it can be changed. Before we can display it in the form, however, we need to convert the HTML breaking returns back into end of lines so that the lines are separated in the textarea.

<?PHP
if($action == "edit") {
    $data = file('news.txt');
    $element = trim($data[$id]);
    $pieces = explode("|", $element);
    //the next line is to reverse the process of turning the end of lines into breaking returns
    $news = str_replace("<BR>","\r\n",$pieces[2]);
    echo "Make the changes you would like and press save.<BR>\n";
    echo "<FORM ACTION=\"$PHP_SELF?action=edit\" METHOD=\"POST\" NAME=\"editform\">\n";
    echo "Name:<BR>\n";
    echo "<INPUT TYPE=\"text\" SIZE=\"30\" NAME=\"name\" value=\"".$pieces[1]."\"><BR>\n";
    echo "The
News:<BR>\n
";
    echo "<TEXTAREA NAME=\"news\" COLS=\"40\" ROWS=\"5\">".$news."</TEXTAREA><BR><BR>\n";
    echo "Password:<BR>\n";
    echo "<INPUT TYPE=\"password\" SIZE=\"30\" NAME=\"password\"><BR>\n";
    echo "<INPUT TYPE=\"hidden\" NAME=\"date\" VALUE=\"".$pieces[0]."\">\n";
    echo "<INPUT TYPE=\"hidden\" NAME=\"id\" VALUE=\"$id\">\n";
    echo "<INPUT TYPE=\"submit\" NAME=\"submit\" VALUE=\"Save\"><BR>\n";
    echo "</FORM>\n";
    exit;
}
?>

Cool, now you can edit that information to your hearts content. Now let's worry about what happens when the Save button is pushed. First off, we need a line of code, similar to the one for the delete section, that checks that the action is edit and the password field has been populated.

<?PHP
if($action == "edit" && isset($HTTP_POST_VARS['password'])) {
?>
 

Next thing is to load the whole file into and array and then change the news item we want to change and finally save it back to the file.

<?PHP
if($action == "edit" && isset($HTTP_POST_VARS['password'])) {
    //obviously you should change this password on the next line
    if($HTTP_POST_VARS['password'] == "editpass") {
        //First let's recompile that line with the pipe symbols so we can reinsert it
        $line = $HTTP_POST_VARS['date'] . "|" . $HTTP_POST_VARS['name'];
        $line .= "|" . $HTTP_POST_VARS['news'];
        $line = str_replace("\r\n","<BR>",$line);
        $line .= "\r\n";
        $data = file('news.txt');
        $data[$id] = $line;
        //the next line makes sure the $data array starts at the beginning
        reset($data);
        //now we open the file with mode 'w' which truncates the file
        $fp = fopen('news.txt','w');
        foreach($data as $element) {
            fwrite($fp, $element);
        }
        fclose($fp);
        echo "Item Edited!<BR><BR>\n";
        echo "<a href=\"$PHP_SELF\">Go Back</a>\n";
        exit;
    } else {
        echo "Bad password!\n";
        exit;
    }
}
?>


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