Using the CodeIgniter PHP web framework – How to create a simple secured blog in 30 minutes

VN:F [1.9.22_1171]
Rating: 4.0/5 (69 votes cast)

This is a beginner’s guide to installing CodeIgniter and creating a simple, secured blog in about 30 minutes. CodeIgniter is an open source MVC web application framework with a very small footprint. Its aim is to enable developing projects much faster than writing code from scratch, by providing a set of libraries for commonly needed tasks, as well as a simple interface and logical structure to access these libraries.

If you’ve not heard about the MVC concept, please read about it first, as you need to know about its basics to be able to understand all parts of this tutorial. Basic knowledge of HTML and PHP will be needed, too.

Although I’ve created this simple blog application on my own web space that‘s was hosted by Hostmonster, using other web hosting companies’ solutions shouldn’t be a problem, if they have PHP and MySQL installed on their servers.
Warning! As I moved my website to an other hosting provider in January 2012, the working examples are no longer available here.


1. Installation

Download CodeIgniter from their website. Unzip it. Create a folder named “yourfolder” (or whatever you want to call it) on your web space inside any www or public_html folder and upload the CodeIgniter folders and files into this folder.

Open the application/config/config.php file with a text editor (I use Notepad++) and set your base URL (e.g. www.yoursite.com/yourfolder – “yoursite.com” being your domain and “yourfolder” is the folder you just uploaded the CodeIgniter files to).

Open the application/config/database.php file with a text editor and set your database settings. Most web hosts provide users with “How to set up your database” guides, if you’re not sure how to do this, look them up on your host’s website.


2. Creating the “blog” controller

Create a file called blog.php in the “controllers” folder. this is going to contain your first custom CodeIgniter controller, called “Blog”.

Add the “index” function to the controller to test it is working…

<?php

class Blog extends Controller {
   function index()
   {
      echo "hey!";
   }
}

?>

Now www.yoursite.com/yourfolder/index.php/blog displays…

hey!

Go, check it out, it should look something like this…
Browser displays "hey!"

3. Making “blog” the default application

The “blog” controller is now working, however www.yoursite.com/yourfolder/ still displays CodeIgniter’s default welcome screen, so let’s change this to your blog’s home page in config/routes.php! Change the following line…

$route['default_controller'] = "welcome";

to…

$route['default_controller'] = "blog";

Now www.yoursite.com/yourfolder/ displays the “hey!” message, too…
ciBlog is the default application

4. Creating the “blog” view

Create a file called blog_view.php in the “views” folder.

Add a few lines of simple HTML (html-head-body) code to blog_view.php, this is still easy enough.

Add the following line to the “index” function created in Step 2 and delete the “echo” line…

$this->load->view('blog_view.php', $data);

…now www.yoursite.com/yourfolder/ displays the HTML you just added to blog_view.php, but it also displays a PHP warning, as the “$data” variable doesn’t exist yet. All in all though, your first custom view is being displayed…
Custom view plus PHP warning

5. Creating dynamic content

Change the content of the “index” function in blog.php to the following…

$data['title'] = "Blog";

$data['h1'] = "Welcome to my blog!";

$data['list'] = array('first', 'second', 'third');

$this->load->view('blog_view.php', $data);

Add the following PHP code to blog_view.php:

E.g.

Create the title in the head…

<title><?php echo $title; ?></title>

…and an ordered list in the body…

<ol>

   <?php foreach($list as $item): ?>

      <li>

         <?php echo $item; ?>

      </li>

   <?php endforeach; ?>

</ol>

www.yoursite.com/yourfolder/ now displays your dynamic title and list…
ciBlog displays dynamic content

6. Database setup

Create a database and a user for it. It is pretty straightforward on Hostmonster, other providers may ask you to do it differently, so again, if you’re not sure, check their website for guides.

Add two tables (“entries” and “comments”) to the database and the fields “id”, “title”, “text” for the entries table, and “id”, “entry_id”, “text”, “author” for the comments table. Set auto increment to TRUE for both of the “id”-s (using phpMyAdmin is good enough to modify the database, but you can use different methods, as well).

Edit the autoload.php config file, to make CodeIgniter auto load the database, otherwise it won’t work…

$autoload['core'] = array('database');

Populate your database with some test data. You could use phpMyAdmin again, or try CodeIgniter’s scaffolding function, but you have to set scaffolding up first! Warning: scaffolding must only be used during development!


7. Setup blog to display data from database

Add a get data query to the “index” function in blog.php (anywhere before the last line of the function), this’ll get all the data from the “entries” table…

$data['query'] = $this->db->get('entries');

Change the PHP foreach section found in blog_view.php to the following…

<?php foreach($query->result() as $row): ?>

   <h3><?php echo $row->title ?></h3>

   <p><?php echo $row->text ?></p>

   <hr />

<?php endforeach; ?>

Now www.yoursite.com/yourfolder/ displays all the sample blog entries with horizontal lines separating them…
ciBlog displays content from database

8. Adding links to a comments page

Create a link in blog_view.php using CodeIgniter’s anchor function and place it into the foreach function, above the horizontal ruler…

<p><?php echo anchor('blog/comments/'.$row->id,
   'Comments'); ?></p>

The anchor function makes creating HTML anchors faster and easier. Great, but it won’t work yet. First you’ll have to call the “url” helper to make it work. It’ll be done in the next step.


9. Creating the comments page (displaying and submitting comments)

You need to load CodeIgniter’s “url” and “form” helpers through blog.php, inside a new function called “Blog”. Place it to the top of the “Blog” class…

function Blog()
{
   parent::Controller();
     
   $this->load->helper('url');
   $this->load->helper('form');
}

The “Comments” links will appear from now on…
Comments links appearLet’s create a “comments” function in the “Blog” class and add the following to it…

$data['title'] = "Comments";
$data['h1'] = "Comments";
$this->load->view('comment_view.php', $data);

To display the comments, a new view is needed to be created, let’s call it comment_view.php. Create it now in the views folder and add the usual sample HTML code to it.

Insert CodeIgniter’s “form_open” and “form_hidden” functions into the body section of the new comment_view.php file…

<?php echo form_open('blog/comment_insert'); ?>
<?php echo form_hidden('entry_id',
   $this->uri->segment(3)); ?>

Add a text area, an author field and a submit button below to finish off the comment form you just started creating…

<p><textarea name="text" rows="10"></textarea></p>
<p><input type="text" name="author" /></textarea></p>
<p><input type="submit" value="Submit" /></textarea></p>

… so it will look like this…
Comment formA function called “comment_insert” needs to be created in blog.php for CodeIgniter’s “form_open” to run it. What the following code does is that it inserts the comment into the “comments” table of the database and redirects the browser to the current comment page, to virtually refresh it. Add this to the “comment_insert” function now…

$this->db->insert('comments', $_POST);
redirect('blog/comments/'.$_POST['entry_id']);

Add the following two lines to the “comments” function (before the last line of the function) to display only the related comments for each blog entry…

$this->db->where('entry_id', $this->uri->segment(3));
$data['query'] = $this->db->get('comments');

Edit comment_view.php to display only the comments related to the blog posts and also add a back link to the blog…

<?php foreach($query->result() as $row): ?>
   <p><?php echo $row->author ?></p>
   <p><?php echo $row->text ?></p>       
   <hr />
<?php endforeach; ?>
<p><?php echo anchor('blog', 'Back to blog'); ?></p>

And that’s it! Check if it’s working or not. When you add a couple of comments, it should look similar to this…
Working comments pageYou should now have a simple blog, that is working properly. It is possible to view blog entries and to comment on them. If you’d like to add bonus functionalities to your application, continue the tutorial below!




10. Adding style, header and footer to all views

Create a header.php and footer.php file in the views folder with obvious content in them.

Edit the “index” function found in blog.php to load the header before blog_view.php and the footer after it…

$this->load->view('header.php');
$this->load->view('blog_view.php', $data);
$this->load->view('footer.php');

Edit the “comments” function the same way to create the same look and delete the now unnecessary HTML bits from “blog_view.php” and “comment_view.php”.


11. Displaying “no comments” message if there are no comments for a blog post

Wrap the “foreach” function in comment_view.php into a PHP “if” function the following way…

<?php if ($query->num_rows() > 0): ?>

   ***
   /* The original foreach function must be placed here. */

   ***

<?php else: ?>

   <p>No comment has been posted for this blog entry.</p>

   <hr />

<?php endif; ?>

… and a no comment page will look like this…
No comments

12. Adding simple security to the comments page

First, you have to turn CodeIgniter’s automatic XSS filter on. It activates every time when GET, POST or COOKIE data is encountered and it stops malicious scripts to be posted in comments. Let’s set it to TRUE in config/config.php…

$config['global_xss_filtering'] = TRUE;

To escape inappropriate HTML inserted into comments, you need to add the “form_prep” function to comment_view.php the following way…

<p><?php echo form_prep($row->author) ?></p>
<p><?php echo form_prep($row->text) ?></p>

This will stop links and other malicious stuff appearing in comments…

No malicious stuff appearingTo also secure the blog against common SQL injection techniques, you must:

a. Edit the “comment_insert” function in blog.php, using the “addslashes” PHP function and creating an “insert_data” array to store the “post” variables for the function…

$post_id = addslashes($_POST['entry_id']);
$post_text = addslashes($_POST['text']);
$post_author = addslashes($_POST['author']);

$insert_data = array('entry_id' => $post_id,
'text' => $post_text, 'author' => $post_author);

$this->db->insert('comments', $insert_data);

b. Edit “comment_view.php”, using the “stripslashes” PHP function to remove added slashes at display…

<p><?php echo stripslashes(form_prep($row->author)) ?></p>
<p><?php echo stripslashes(form_prep($row->text)) ?></p>

After all these modifications if a malicious comment is entered, e.g.:

SQL injection: '); DROP TABLE users; <a href="
http://www.yoursite.com/yourfolder/
index.php/blog">Back to blog</a>
<script>var i=9;</script>

… it’ll be displayed like this…

A filtered malicious comment… and the database will store it as…

SQL injection: \'); DROP TABLE users; <a href=\"
http://www.yoursite.com/yourfolder/
index.php/blog\">Back to blog</a>
[removed]var i=9;[removed]

… so your function is secured against most SQL injection attacks.

Check out the working application here.


Using the CodeIgniter PHP web framework - How to create a simple secured blog in 30 minutes, 4.0 out of 5 based on 69 ratings
 

Comments are closed.