How to Create a SEO Friendly URL in CodeIgniter

Installing CodeIgniter

If you don't have CodeIgniter installed yet, you can use this link to download the latest version of CodeIgniter. Note: I'm using version 3.1.7 in this tutorial. After downloading, extract the file in the folder of your server. Since I'm using XAMPP as my localhost server, I've put the folder in htdocs folder of my XAMPP. Then, you can test whether you have successfully installed codeigniter by typing your app name in your browser. In my case, I named my app as ci_seo_url so I'm using the below code.
  1. localhost/ci_seo_url
codeigniter successful install

Removing index.php in our URLs

By default, index.php is included in every URL of our app. To remove this, please refer to my tutorial How to Remove Index.Php in the URL of Codeigniter Application.

Creating our Database

I've included a .sql file located in db folder in the downloadable of this tutorial. All you need to do is import the file into your phpMyAdmin. If you have no idea how to import, please refer to my tutorial How import .sql file to restore MySQL database. You should be able to add a database named db.

Connecting our App into our Database

Next, we're going to connect our codeigniter application to the database that we created earlier. 1. In your codeigniter app folder, open database.php located in application/config folder. 2. Update database.php with your credential the same as what I did below.
  1. $db['default'] = array(
  2.         'dsn'   => '',
  3.         'hostname' => 'localhost',
  4.         'username' => 'root',
  5.         'password' => '',
  6.         'database' => 'db',
  7.         'dbdriver' => 'mysqli',
  8.         'dbprefix' => '',
  9.         'pconnect' => FALSE,
  10.         'db_debug' => (ENVIRONMENT !== 'production'),
  11.         'cache_on' => FALSE,
  12.         'cachedir' => '',
  13.         'char_set' => 'utf8',
  14.         'dbcollat' => 'utf8_general_ci',
  15.         'swap_pre' => '',
  16.         'encrypt' => FALSE,
  17.         'compress' => FALSE,
  18.         'stricton' => FALSE,
  19.         'failover' => array(),
  20.         'save_queries' => TRUE
  21. );

Creating our Model

Next, we create the model for our app. Take note that the first letter of your model name should be in CAPITAL letter and the name of the model should be the same as the file name to avoid confusion. Create a file named Posts_model.php in application/models folder of our app and put the ff codes:
  1. <?php
  2. defined('BASEPATH') OR exit('No direct script access allowed');
  3.  
  4. class Posts_model extends CI_Model {
  5.         public function __construct(){
  6.                 parent::__construct();
  7.                 $this->load->database();
  8.         }
  9.         public function fetchAllPost(){
  10.                 $query = $this->db->get('posts');
  11.                 return $query->result();
  12.         }
  13.         public function insertPost($data){
  14.                 return $this->db->insert('posts', $data);
  15.         }
  16.         public function getPost($slug){
  17.                 $query = $this->db->get_where('posts', array('post_slug'=>$slug));
  18.                 return $query->row_array();
  19.         }
  20. }

Creating our Controller

Next step is to create our controller. Controllers follow the same naming convention as models. Create a file named Posts.php in application/controllers folder of our app and put the ff codes.
  1. <?php
  2. defined('BASEPATH') OR exit('No direct script access allowed');
  3.  
  4. class Posts extends CI_Controller {
  5.         public function __construct(){
  6.                 parent::__construct();
  7.                 $this->load->helper('url');
  8.                 $this->load->model('posts_model');
  9.                 $this->load->library('session');
  10.         }
  11.         public function index(){
  12.                 $data['posts'] = $this->posts_model->fetchAllPost();
  13.                 $this->load->view('show_post', $data);
  14.         }
  15.  
  16.         public function addPost(){
  17.                 $posts['title'] = $this->input->post('post_title');
  18.                 $posts['post_text'] = $this->input->post('post_text');
  19.                
  20.                 //create slug
  21.                 $posts['post_slug'] = $this->slugify($posts['title']);
  22.                
  23.                 //insert post
  24.                 $query = $this->posts_model->insertPost($posts);
  25.  
  26.                 if($query){
  27.                         redirect('/');
  28.                 }
  29.         }
  30.  
  31.         public function slugify($string){
  32.                 //remove prepositions
  33.         $preps = array('in', 'at', 'on', 'by', 'into', 'off', 'onto', 'from', 'to', 'with', 'a', 'an', 'the');
  34.                 $pattern = '/\b(?:' . join('|', $preps) . ')\b/i';
  35.                 $string = preg_replace($pattern, '', $string);
  36.  
  37.         // replace non letter or digits by -
  38.         $string = preg_replace('~[^\\pL\d]+~u', '-', $string);
  39.  
  40.         // trim
  41.         $string = trim($string, '-');
  42.  
  43.         // transliterate
  44.         $string = iconv('utf-8', 'us-ascii//TRANSLIT', $string);
  45.  
  46.         // lowercase
  47.         $string = strtolower($string);
  48.  
  49.         // remove unwanted characters
  50.         $string = preg_replace('~[^-\w]+~', '', $string);
  51.  
  52.        
  53.  
  54.                 if (empty($string)){
  55.                 return 'n-a';
  56.         }
  57.  
  58.         return $string;
  59.     }
  60.  
  61.     public function view($slug){
  62.         $data['post_row'] = $this->posts_model->getPost($slug);
  63.         $this->load->view('view_post', $data);
  64.     }
  65.  
  66. }

Creating our Routes

Next, we are going to set up the routes of our application. Open routes.php located in application/config folder and update it with the codes below to setup our default route and post route.
  1. $route['default_controller'] = 'posts';
  2. $route['404_override'] = '';
  3. $route['translate_uri_dashes'] = FALSE;
  4.  
  5. //view post
  6. $route['post/(:any)'] = 'posts/view/$1';

Creating our Views

Lastly, we create the views of our app. Take note that I've use Bootstrap in the views which is included in the downloadables of this tutorial. But if you want, you may download bootstrap using this link. Create the ff files inside application/views folder. show_post.php
  1. <!DOCTYPE html>
  2. <html>
  3. <head>
  4.         <meta charset="utf-8">
  5.         <title>How to Create a SEO Friendly URL in CodeIgniter</title>
  6.         <link rel="stylesheet" type="text/css" href="<?php echo base_url(); ?>bootstrap/css/bootstrap.min.css">
  7. </head>
  8. <body>
  9. <div class="container">
  10.         <h1 class="page-header text-center">Create a SEO Friendly URL in CodeIgniter</h1>
  11.         <div class="row">
  12.                 <div class="col-sm-3">
  13.                         <h3 class="text-center">Add New Post</h3>
  14.                         <br>
  15.                         <form method="POST" action="<?php echo base_url(); ?>posts/addPost">
  16.                                 <div class="form-group">
  17.                                         <label>Post Title:</label>
  18.                                         <input type="text" class="form-control" name="post_title" required>
  19.                                 </div>
  20.                                 <div class="form-group">
  21.                                         <label>Post Text:</label>
  22.                                         <textarea class="form-control" name="post_text" rows="5" required></textarea>
  23.                                 </div>
  24.                                 <button type="submit" class="btn btn-primary">Submit</button>
  25.                         </form>
  26.                 </div>
  27.                 <div class="col-sm-9">
  28.                         <table class="table table-bordered">
  29.                                 <thead>
  30.                                         <th>PostID</th>
  31.                                         <th>Title</th>
  32.                                         <th></th>
  33.                                 </thead>
  34.                                 <tbody>
  35.                                 <?php
  36.                                         foreach($posts as $post){
  37.                                                 echo "
  38.                                                         <tr>
  39.                                                                 <td>".$post->id."</td>
  40.                                                                 <td>".$post->title."</td>
  41.                                                                 <td><a href='".base_url()."post/".$post->post_slug."' class='btn btn-info btn-sm'>View</a></td>
  42.                                                         </tr>
  43.                                                 ";
  44.                                         }
  45.                                 ?>
  46.                                 </tbody>
  47.                         </table>
  48.                 </div>
  49.         </div>
  50. </div>
  51. </body>
  52. </html>
view_post.php
  1. <!DOCTYPE html>
  2. <html>
  3. <head>
  4.         <meta charset="utf-8">
  5.         <title>How to Create a SEO Friendly URL in CodeIgniter</title>
  6.         <link rel="stylesheet" type="text/css" href="<?php echo base_url(); ?>bootstrap/css/bootstrap.min.css">
  7. </head>
  8. <body>
  9. <div class="container">
  10.         <h1 class="page-header text-center">Create a SEO Friendly URL in CodeIgniter</h1>
  11.         <div class="row">
  12.                 <div class="col-sm-8 col-sm-offset-2">
  13.                         <h5><b>Title:</b> <?php echo $post_row['title']; ?></h5>
  14.                         <p><b>Text:</b> <?php echo $post_row['post_text']; ?></p>
  15.                 </div>
  16.         </div>
  17. </div>
  18. </body>
  19. </html>
That ends this tutorial. Happy Coding :)

Add new comment