Flatfile PHP simple CMS tutorial Part 2 the code

This is part two of our simple CMS or blog in flatfile format. We’ll see how to structure the flat file, and the code needed to read it in.

This code is not optimized, so it’s easier to understand. As we progress in this series we’ll see how to improve coding style.

First of all we have to define the flat file format.

We will need several fields:

  1. Title – mandatory
  2. Url – mandatory
  3. Content – mandatory
  4. Meta keywords – optional
  5. Meta description – optional
  6. Author – optional
  7. Post date – optional, as unix timestamp

The most straightforward way to tackle this in a flat file would be to separate each element with a special character never to be used in titles or content, say a pipe symbol ‘|’.

Then, we would place all content on a single row and use PHP’s fgets() function to read one line at a time.

There are two problems with this approach: sometimes is handy to include newlines in the file, to make it easier to read and edit. And using a special character, whatever it is, prevents us from using it in the text.

A nice and tidy solution would be to use some sort of XML format, but we are aiming for a short, efficient script -not an exercise in Quality Coding.

A good compromise can be to use a complex separator both for articles and for items inside articles. Let’s say something like: #00# between items and #99# between articles.

The “database” file would therefore appear this way:

Looks like a mess, right? Let’s make a simple entry template:


[anything here will be the post]


Just copy and paste this block to add an entry, then fill in the fields.

As you can see the home page in the first example is marked with a single slash, as using index.html is usually bad for SEO.

How are we going to parse this flat file database in PHP?

First of all, we’ll have to read the file in memory. Then, explode articles and iterate over them. If an article matches the url the user requested, explode this article contents and fill the “Theme”.

To make everything clean and expandable, we’ll begin defining some config variables. Please note this code is very basic so that it’s easier to understand, and is compatible with PHP4 (BTW, if you are using PHP4 upgrade NOW). Feel free to optmize it if you are an experienced programmer.

With this code, we’ll have $found set to true and the $items array filled if the page was in the database.

We’ll complete the script in the next post, handling 404 errors and implementing the template system.

Posted in Complete Scripts

Leave a Reply

Your email address will not be published. Required fields are marked *