Using files as a news data store
While working on the new portal I have been storing the page content and news items in plain text files. From a personal perspective this has advanced my understanding of handling files in php rather than setting up the usual CRUD functions to talk a databse.
I have set up two folders: one to hold the page content for the site and the other to hold the news items (which I aim to provide as an on-demand rss feed).
For news items the file name is the timestamp when the item was created. To begin with news items have the extension .draft e.g.
news/1428418595.draft news/1427796439.draft
The first line of the file is the headline, the second line is the strapline and the rest of the file is the actual story. I’ll need to strip stray \n entries from the headline and strapline to keep the file structured correctly. e.g.
A big headline Say something about the story From here on there will be HTML
Once the news item is to be published the file is simply renamed to remove the .draft extension.
All of this should be transparent to the user. Here is an example of how the News Manager looks to the end user:
The buttons are Delete, Edit, Preview and the thumb up icon next to draft allows the user to publish the story.
I am also asking the end user to provide an optional 100×100 thumbnail to associate with the news item. I’m allowing any valid image file to be used although it should be square to begin with because I just hard resize and convert to jpg using ImageMagick.
$cmd .= 'convert -resize 100x100! '.$target_file.' '.$target_file.''; system ($cmd);
I’m going to change the system command to use php5 ImageMagick later on (when I work out how to use it!):
$im = new Imagick(); $im->setResolution( 100, 100 );
Not surprisingly, the thumbnail is stored along with the news file with the same name and the extension .jpg:
news/1428418595.draft.jpg
This has nothing to do with the images which may be contained within the new story (more on that in a later post).
There are some interesting challenges to listing the news stories in the News Manager. My preferred text editor KATE creates temp files which have to be ignored (during development). The jpg files must also be ignored when listing stories. For each filename in the news folder here is the test used to ignore such files:
if((substr($newsfile,-4,4)!='.jpg')&&(substr($newsfile,-4,4)!='-swp')) { // list the file - it's news - now check if it's draft or published }
I will remove the -tmp test when the site is finished as I won’t be editing any news files directly with KATE then.
From a security perspective I will most likely move the news and content files out of the web root and use some kind of proxy retrieval (like Moodle’s file.php). I will also log user actions and use public/private keys to authorise edits as well as requiring the user to be logged as staff to the LearnNet system before they even get to see the news manager.