PDA

View Full Version : Tutorial: PHP news system.



ashleycox
23 May 2011, 03:12 PM
In this tutorial, I'm going to show you a basic news system. The system is entirely flat-files, and doesn't use a database. Here are the features our news system will have:
News categories
the ability to add articles and categories
rss feeds for each category
static pages
Full meta keyword and description support

A note: this tutorial aims to teach you how to create a functioning news system. It's not a complete feature rich system, nore does it look pretty. It will need completing, and definetly a bit of styling.

Let's get started:

First, create a folder called "news_system" or whatever you like. Inside this folder, create these files/folders:
Folder: category
Folder: files
file: header.php
file: index.php

The 'category' folder is going to be the folder where the directories for our categories are going to be stored. We don't want our visiters to be able to enter this folder, so inside this folder, create a file called 'index.php' with this code in it:
<?php header ("location: ../index.php"); ?>
This will return the visiter to the article system homepage if they atempt to access the category folder.

The 'files' folder will hold files necessary for the categories to opperate properly once created. Inside the 'files folder, create the following files: feed.php, category_template.php, and index.php. Put this inside category_template.php:
<?php $file_name = basename(dirname(__FILE__)); $file_name_2 = STR_REPLACE ("-", " ", $file_name);
<html> <head> <title><?php echo $file_name_2; ?></title></head> <body> <?php echo "<h1>Viewing Articles in category:" . $file_name_2 . "</H1>"; echo "<p>Below are the articles in your selected category</p>"; if ($handle = opendir(getcwd())) {
while (false !== ($file = readdir($handle))) {
if ($file != '.' && $file != '..') {
$fileName = str_replace('.php', '', $file);
$fileName = str_replace ('_', ' ', $fileName);
if($file != 'index.php' ) {
echo '<a href="' . $file . '">' . $fileName . '</a>';
} }
}
closedir($handle);
}
?> <a href="../../index.php">Back to News home</a> </body> </html>

This is the main page for our categories. It shows a list of all the articles (static php files) in the folder that the script is in.

Inside feed.php put this:

<?php
$cattitle = basename(dirname(__FILE__));
$desc = "Rss feed for category";
$subdir = substr ($_SERVER["PHP_SELF"], 0, strrpos ($_SERVER["PHP_SELF"], "/"));
$uri = "http://".$_SERVER["HTTP_HOST"].$subdir;
//$path = $_SERVER["DOCUMENT_ROOT"].$subdir;
$path = "./";
function translate ($string) {
$title = str_replace (".php", "", $string);
return $title;
}
header ("Content-type: text/xml");
echo "<?xml version=\"1.0\"?>\n";
echo "<rss version=\"2.0\">\n";
echo "<channel>\n";
echo "<title>".htmlentities ($cattitle)."</title>\n";
echo "<link>$uri</link>\n";
echo "<description>".htmlentities ($desc)."</description>\n";
$d = opendir ($path);
while (false !== ($entry = readdir($d))) {
$filespec = $path.$entry;
$fs = 0;
$pos = strlen ($filespec) - 4;
if (is_file ($filespec))
if (strpos ($filespec, ".php", $pos) == $pos) {
$fs = filesize ($filespec);
if ($fs > 0) {
$file [translate ($entry)] = filemtime ($filespec);
}
}
}
closedir ($d);
arsort ($file);
foreach ($file as $entry => $timestamp) {
$filespec = $path.$entry;
$title = ucwords (str_replace ("_", " ", $entry));
$url = $uri."/".$entry.".php";
$pubdate = date ("M j Y g:i A", $timestamp);
$fs = filesize ($filespec.".php");
echo "<item>\n";
echo "<pubDate>$pubdate</pubDate>\n";
echo "<title>$title</title>\n";
echo "<link>$url</link>\n";
if ($desc = @file_get_contents ($filespec.".txt"))
echo "<description>".htmlentities ($desc)."</description>\n";
echo '<enclosure url="'.$url.'" length="'.$fs.'" type="audio/mpeg" />';
echo "</item>\n";
}

echo "</channel>\n";
echo "</rss>\n";
?>

This file, similar to the category template file, gets a list of all the php files in the directory and puts them into an rss feed, in order of the most recently added file to the oldest.

Lastly, inside index.php, put this:
<?php header ("location: ../index.php"); ?>
This file is exactly the same as the file inside our category folder, it takes the user directly back to the homepage if they try to access the files folder. And that's it, we're done with the files folder.

Now for our main index.php. In the 'news_system' folder or whatever you named it, open your index.php file and put this code:

<html><head><title>News</title></head><body> <h1>News</h1><p>Select a category below to view the articles in that category.</p><h2>Categories:</h2> <?php foreach(glob('category/*', GLOB_ONLYDIR) as $dir) { $dir = basename($dir); $the_category = STR_REPLACE ("-", " ", $dir); echo '<a href="category/', $dir, '">', $the_category, '</a>'; } ?> </body></html>

This is a very simple page. It simply shows the user a page where they can select from a list of categories. The script grabs a list of th edirectories inside our 'category' folder, and shows a list of links to these directories. When a user clicks on one of these links, the script sends the user to our category_template file, inside the categories directory. Simples!

Lastly, open 'header.php' and put this code in it:
<?php
$currentFile = STR_REPLACE ('.php', '', $_SERVER['SCRIPT_NAME']); $pagetitle = STR_REPLACE ('_', ' ', $currentFile); $parts = Explode('/', $pagetitle); $pagetitle = $parts[count($parts) - 1]; ?> <html> <head> <title><?php echo $pagetitle ?></title>

This is a header piece for our articles. This will be included in all the articles we create.

Only 2 more files to go! Create 2 more files in teh main directory of your news system. Call them addcategory.php and writearticle.php.

Put this in addcategory.php:

<html><head><title>Add Category</title></head><body> <h1>Add Category</h1> <?php if(isset($_POST['submit'])) {
$thisdir = getcwd(); $name = STR_REPLACE (" ", "-", $_POST['categoryname']); $dir = 'category/' . $name; if(mkdir('category/' . $name, 0777)) { copy('files/category_template.php',$dir . '/index.php'); copy('files/feed.php',$dir . '/rss_feed.php'); echo 'Your category (' . $name . ') Was successfully created! <a href="addcategory.php">Add Another</a> or <a href="index.php">Back to news home</a>'; } } else {
echo '<form action="addcategory.php" method="post">';
echo 'Category Name: <input type="text" name="categoryname" id="categoryname">'; echo '<input type="submit" name="submit" value="Add"></form>'; } ?></body></html>

This page takes the category name you input from a form, and creates the category directory inside the 'category' folder. If it successfully creates the directory, it copy's the category_template.php and feed.php files into this folder, and names them appropriately.

Now for the last part; the writearticle.php file. open this file and put this code in it:

<head><title>Write Article</title></head> <body><?php
echo "<h1>Write Article</h1>"; if(isset($_POST['submit'])) { $your_data = $_POST['article'];
$directory = $_POST['category'] . '/';
$filename = str_replace (" ", "_", $_POST['articlename'] . '.php');
$header = "<?php include \"../../header.php\"; ?>";
$header2 = "<body> <h1><?php echo $pagetitle ?></h1> <br><br>";
$footer = "</body> </html>";
$metadesc = '<meta name="description" content="' . $_POST['description'] .
'">';
$metakeywords = '<meta name="keywords" content="' . $_POST['keywords'] .
'">';
$name = '<p>Posted: ' . date('Y-m-d') . '</p>';
$fp = fopen('category/' . $directory.$filename, "w");
fwrite($fp, $header);
fclose($fp);
$fp = fopen('category/' . $directory.$filename, "a");
fwrite($fp, $metadesc);
fclose($fp);
$fp = fopen('category/' . $directory.$filename, "a");
fwrite($fp, $metakeywords);
fclose($fp);
$fp = fopen('category/' . $directory.$filename, "a");
fwrite($fp, $header2);
fclose($fp);
$fp = fopen('category/' . $directory.$filename, "a");
fwrite($fp, $name);
fclose($fp);
$fp = fopen('category/' . $directory.$filename, "a");
fwrite($fp, $your_data);
fclose($fp);
$fp = fopen('category/' . $directory.$filename, "a");
fwrite($fp, $footer);
fclose($fp);
?>
<p>Your article was successfully posted!</p> <a href="category/<?php echo $directory; echo $filename; ?>">View your article</a> <a href="index.php">Back to news home</a>
<?php
} else {
?>
<form action="writearticle.php" method="post">
Article name: <input type="text" name="articlename" id="articlename">
category: <select name="category" id="category">
<?php
foreach(glob('../news/category/*', GLOB_ONLYDIR) as $dir)
{
$dir = basename($dir);
$thecategoryname = STR_REPLACE ("-", " ", $dir);
echo '<option value="', $dir, '">', $thecategoryname, '</option>';
}
?>
</select>
<p>Can't see the right category? <a href="addcategory.php">Add A New Category</a></p>
Description: <input type="text" name="description">
Keywords (comma and space separated): <input type="text" name="keywords">
Article: <textarea name="article" id="article"> </textarea>
<input type="submit" name = "submit" value="post!">
</form>
<?php } ?>
</body></html>

This file is pretty self-explanatory; if the form was submitted, it takes the input from the form, splits it up, and then writes a static page inside the category you selected, containing the various parts. If the form wasn't submitted, it displays the form.


Note! you may want to protect the 'addcategory.php' and 'writearticle.php' files with a log-in system, to stop anybody editing them.

And that's it; if you followed this correctly, you should have this directory structure:
/
/category/
/category/index.php
/files/
/files/feed.php
/files/category_template.php
/files/index.php
/index.php
/addcategory.php
/writearticle.php
/header.php

Hope you enjoyed this tutorial, your comments are greatly appreciated!

robertadico
13 Dec 2012, 06:49 AM
want some more detail about this post...........


Real Kanban (http://www.yooarticles.net/article/two-day-certified-scrum-master-training-course-will-get-you-qualified)

SASAtechno
13 Dec 2012, 07:33 AM
Thank you for share this information this is helpful to everyone....

lemuelmayers
19 Dec 2012, 07:26 PM
I really want to know more about this PHP news system and I want to learn it better since it could help me improving my page.

James_Smith
18 Feb 2013, 07:02 AM
It's a nice effort to understand about the PHP news system and gives us a basic idea about it. Is there any other resource to know details about it? If you may know anything then share here. Great work, keep it up. Looking more such a great stuff from you.